Python matplotlib.patches.Patch() Examples

The following are code examples for showing how to use matplotlib.patches.Patch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: DataComp   Author: Cojabi   File: visualization.py    Apache License 2.0 6 votes vote down vote up
def create_legend(labels, colors):
    """
    Creates a legend for plots using the given colors and labels.

    :param labels: Iterable of labels that shall be used in the legend.
    :param colors: Iterable of colors that shall be used in the legend.
    :return:
    """
    patches = []

    for color, label in zip(colors, labels):
        patches.append(mpatches.Patch(color=color, label=label))

    plt.legend(handles=patches, prop={'size': 12})

## longitudinal plotting 
Example 2
Project: recaptcha-cracker   Author: nocturnaltortoise   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_query_amounts(captcha_queries, query_amounts):
    queries_and_amounts = zip(captcha_queries, query_amounts)
    queries_and_amounts = sorted(queries_and_amounts, key=lambda x:x[1], reverse=True)
    captcha_queries, query_amounts = zip(*queries_and_amounts)

    # colours = cm.Dark2(np.linspace(0,1,len(captcha_queries)))
    # legend_info = zip(query_numbers, colours)
    # random.shuffle(colours)
    # captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries] 
    bars = plt.bar(left=range(len(query_amounts)), height=query_amounts)
    plt.xlabel('CAPTCHA queries.')
    plt.ylabel('Query frequencies.')
    plt.xticks([])
    # plt.xticks(range(len(captcha_queries)), captcha_queries, rotation='vertical')
    
    # colours = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', ]

    patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
    plt.legend(handles=patches)

    for i, bar in enumerate(bars):
        bar.set_color(colours[i])
    
    plt.show() 
Example 3
Project: recaptcha-cracker   Author: nocturnaltortoise   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_correct_captchas(captcha_queries, correct_captchas):
    queries_and_correct_scores = zip(captcha_queries, correct_captchas)
    queries_and_correct_scores = sorted(queries_and_correct_scores, key=lambda x:x[1], reverse=True)
    captcha_queries, correct_captchas = zip(*queries_and_correct_scores)

    captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries]
    bars = plt.bar(left=range(len(correct_captchas)), height=correct_captchas)

    patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
    plt.legend(handles=patches)
    plt.xticks([])

    for i, bar in enumerate(bars):
        bar.set_color(colours[i])

    plt.show()

# graph_correct_captchas(captcha_queries, correct_captchas)
# graph_query_amounts(captcha_queries, query_amounts) 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: spines.py    MIT License 6 votes vote down vote up
def set_color(self, c):
        """
        Set the edgecolor.

        Parameters
        ----------
        c : color

        Notes
        -----
        This method does not modify the facecolor (which defaults to "none"),
        unlike the `Patch.set_color` method defined in the parent class.  Use
        `Patch.set_facecolor` to set the facecolor.
        """
        self.set_edgecolor(c)
        self.stale = True 
Example 5
Project: scanomatic   Author: Scan-o-Matic   File: phenotype_results.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_phases_legend(f=None, colors=None):

    if f is None:
        f = plt.figure("Phases legend")
    else:
        f.clf()

    if colors is None:
        colors = PHASE_PLOTTING_COLORS

    ax = f.gca()

    legend = []
    for phase in CurvePhases:
        if phase is CurvePhases.Multiple:
            continue

        legend.append(mpatches.Patch(color=colors[phase], label=re.sub(r"([a-z])([A-Z])", r'\1 \2', phase.name)))

    ax.legend(handles=legend, loc='center', fontsize='large', markerscale=0.66, ncol=2,
              bbox_to_anchor=(0., 0., 1., 1.), borderaxespad=0)

    ax.axis("off")

    return f 
Example 6
Project: HuffmanCompression   Author: jacobhallberg   File: encode.py    MIT License 6 votes vote down vote up
def plot(self, size_l):
        # Increase font size beacuse of resolution.
        x_data = ["Original File", "Our Implementation", "Theoretical Limit"]
        y_data = size_l

        # Create 1x1 area and plot.
        axes = self.figure.add_subplot(1, 1, 1)
        axes.bar(x_data, y_data, width=.5)
        # axes.legend(('r','g','b'), ('Original File', 'My Implementation', 'Thoeretical Limit'))
        # red_patch = mpatches.Patch(color='red', label='The red data')
        # axes.legend(handles=[red_patch])
        for i, v in enumerate(size_l):
            axes.text(i - .1, v + 35, str(v), color='red', fontweight='bold')
        axes.set_ylabel("Size (bits)", fontsize=18)
        axes.set_xlabel("Compression Type", fontsize=18)
        self.draw() 
Example 7
Project: cnvfinder   Author: ip4-team   File: ideogram.py    MIT License 5 votes vote down vote up
def add_legend(self, to_patches: list, loc='lower right', **kwargs):
        """
        Create a legend base on to_patches list

        :param list to_patches: list of dict -> {color: color, label: label}
        :param str loc: legend location
        :param kwargs: are passed to pyplot.legend
        """
        patches = [Patch(color=p['color'], label=p['label']) for p in to_patches]
        self.fig.legend(handles=patches, loc=loc, **kwargs) 
Example 8
Project: LaserTOF   Author: kyleuckert   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'return a list of patch instances in the legend'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 9
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'Return a list of `~.patches.Patch` instances in the legend.'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 10
Project: tenpy   Author: tenpy   File: benchmark.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_many_results(filenames, fn_beg_until="_", fn_end_from="_l_", save=True):
    """Plot files with similar beginning and ending filenames together."""
    import matplotlib.pyplot as plt
    figs = {}
    for fn in filenames:
        fn_beg = fn[:fn.find(fn_beg_until)]
        fn_end = fn[fn.find(fn_end_from):]
        fig_key = fn_beg, fn_end
        if fig_key not in figs:
            fig = plt.figure()
            ax = plt.gca()
            figs[fig_key] = (fig, {}, {})
        fig, color_map, linestyle_map = figs[fig_key]
        plot_result(fn, fig.axes[0], color_map, linestyle_map)
    for fn_key, (fig, color_map, linestyle_map) in figs.items():
        ax = fig.axes[0]
        ax.set_title(fn_key)
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlabel("size")
        ax.set_ylabel("wallclock time (s)")
        # add legend
        patches = []
        labels = []
        import matplotlib.patches as mpatches
        for key in sorted(color_map):
            patches.append(mpatches.Patch(color=color_map[key]))
            labels.append(key)
        import matplotlib.lines as mlines
        for key in sorted(linestyle_map):
            patches.append(mlines.Line2D([], [], linestyle=linestyle_map[key], color='k'))
            labels.append("{s:d} sectors".format(s=key))
        ax.legend(patches, labels)
    if save:
        for key, (fig, _, _) in figs.items():
            fn_beg, fn_end = key
            fn = fn_beg + '_plot' + fn_end[:-4] + '.png'
            fig.savefig(fn)
    else:
        plt.show() 
Example 11
Project: Cubix   Author: doctorfields   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def persistence_diagram(self, dimensions="all"):
        """ Persistence diagram plot"""
        CLASSES_COLORS = {
            0: 'red',
            1: 'green',
            2: 'fuchsia',
            3: 'blue',
            4: 'turquoise',
            5: 'lime',
            6: 'purple',
            7: 'gold',
            8: 'brown',
            9: 'navy',
        }

        MAX_COLORS = len(CLASSES_COLORS)

        if dimensions == "all":
            dimensions = range(self.dimension + 1)

        plt.title("Persistence diagram")
        plt.plot((0, 1), (0, 1), color='gray')
        plt.xlim([-0.05, 1.05])
        plt.ylim([-0.05, 1.05])
        handles = []
        for dim in dimensions:
            if not self.holes[dim]:
                continue
            for hclass in self.holes[dim]:
                x = [hclass.born, hclass.born]
                y = [hclass.born, hclass.death]
                plt.plot(x, y, linewidth=2.0,
                         color=CLASSES_COLORS[dim % MAX_COLORS])
            handles.append(mpatches.Patch(color=CLASSES_COLORS[
                           dim % MAX_COLORS], label='H%d' % dim))
        plt.legend(handles=handles, loc=4)
        plt.show() 
Example 12
Project: Cubix   Author: doctorfields   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def bar_code(self, dimensions="all"):
        """ Bar code plot """
        CLASSES_COLORS = {
            0: 'red',
            1: 'green',
            2: 'fuchsia',
            3: 'blue',
            4: 'turquoise',
            5: 'lime',
            6: 'purple',
            7: 'gold',
            8: 'brown',
            9: 'navy',
        }

        MAX_COLORS = len(CLASSES_COLORS)

        if dimensions == "all":
            dimensions = range(self.dimension + 1)

        plt.title("Bar code")
        handles = []
        height = 1
        for dim in dimensions:
            if not self.holes[dim]:
                continue
            for hclass in self.holes[dim]:
                x = [hclass.born, hclass.death]
                y = [height, height]
                plt.plot(x, y, linewidth=2.0,
                         color=CLASSES_COLORS[dim % MAX_COLORS])
                height += 1
            handles.append(mpatches.Patch(color=CLASSES_COLORS[
                           dim % MAX_COLORS], label='H%d' % dim))
        plt.xlim([-0.05, 1.05])
        plt.ylim([-0.05, height + 0.05])
        plt.legend(handles=handles, loc=4)
        plt.show() 
Example 13
Project: Cubix   Author: doctorfields   File: Plotter.py    GNU General Public License v3.0 5 votes vote down vote up
def set_legend(self, n):
        self.axes.legend(handles=[mpatches.Patch(color=self.colors[dim], label='H%d' % dim) for dim in range(n)], loc=4) 
Example 14
Project: dart_board   Author: astroJeff   File: plot_system_evolution.py    MIT License 5 votes vote down vote up
def plot_k_type(ax_1, ax_2, ax_k_type_list, times, k1_out, k2_out):


    k_type_colors = ['plum', 'sandybrown', 'lightseagreen', 'moccasin', 'chartreuse',
                     'deepskyblue', 'gold', 'rosybrown', 'm', 'darkgreen', 'grey',
                     'sienna', 'palevioletred', 'navy', 'tan', 'black']
    k_type = ['MS conv', 'MS', 'HG', 'GB', 'CHeB', 'EAGB', 'TPAGB', 'HeMS', 'HeHG',
              'HeGB', 'HeWD', 'COWD', 'ONeWD', 'NS', 'BH', 'no remnant']

    # k-type plots
    for a in [ax_1, ax_2]:

        a.axis('off')

        for j,k in enumerate(np.unique(k1_out)):
            a.fill_between(times[k1_out == k], 0.7, 0.9, color=k_type_colors[k])
        for j,k in enumerate(np.unique(k2_out)):
            a.fill_between(times[k2_out == k], 0.4, 0.6, color=k_type_colors[k])

        a.set_title('Stellar Type')

        a.set_xlim(np.min(times), np.max(times))



    # Add legend
    ax_k_type_list.axis('off')
    k_type_all = np.unique(np.array([k1_out, k2_out]))
    patches = [ mpatches.Patch(color=k_type_colors[k], label=k_type[k]) for k in k_type_all ]
    leg = ax_k_type_list.legend(handles=patches, mode='expand', ncol=len(k_type_all))
    leg.get_frame().set_alpha(0.0) 
Example 15
Project: deepJDOT   Author: bbdamodaran   File: utlis.py    MIT License 5 votes vote down vote up
def plot_embedding(X, y, d, title=None, save_fig=0, pname=None):
    """Plot an embedding X with the class label y colored by the domain d."""
    x_min, x_max = np.min(X, 0), np.max(X, 0)
    X = (X - x_min) / (x_max - x_min)
    # Plot colors numbers
    plt.figure(figsize=(10,10))
    ax = plt.subplot(111)
    for i in range(X.shape[0]):
#        plot colored number
#        plt.text(X[i, 0], X[i, 1], str(y[i]),
#                 color=plt.cm.bwr(d[i] / 1.),
#                 fontdict={'weight': 'bold', 'size': 9})
        if d[i]==0:
            c = 'red'
        elif d[i]==1:
            c = 'green'
        elif d[i]==2:
            c = 'blue'
            
        plt.text(X[i, 0], X[i, 1], str(y[i]),
                 color= c,
                 fontdict={'weight': 'bold', 'size': 9})

    plt.xticks([]), plt.yticks([])
    red_patch = mpatches.Patch(color='red', label='Source data')
    green_patch = mpatches.Patch(color='green', label='Target data')
    plt.legend(handles=[red_patch, green_patch])
    plt.show()
    if title is not None:
        plt.title(title)
    if save_fig:
        fname = title+'.png'
        if pname is not None:
            fname = os.path.join(pname, fname) 
        plt.savefig(fname) 
Example 16
Project: PlotSummary   Author: MartinPaulEve   File: text.py    MIT License 5 votes vote down vote up
def plot_terms_two_groups(self, terms, term_name, second_terms, second_term_name, caption, **kwargs):

        """
        War vs. peace terms.
        """

        g1 = terms
        g2 = second_terms

        for term in g1:
            kde = self.kde(self.stem(term), **kwargs)
            plt.plot(kde, color='#e8a945', label=term_name)

        for term in g2:
            kde = self.kde(self.stem(term), **kwargs)
            plt.plot(kde, color='#0067a2', label=second_term_name)

        plt.xlabel('Word Offset')
        plt.ylabel('Number of Occurrences')
        plt.title(caption)

        w_patch = mpatches.Patch(color='#e8a945', label=term_name)
        p_patch = mpatches.Patch(color='#0067a2', label=second_term_name)
        plt.legend(handles=[w_patch, p_patch], loc='upper right')

        fig = plt.gcf()
        fig.set_size_inches(10, 4)
        fig.tight_layout()

        return plt 
Example 17
Project: gtd   Author: JeffAbrahamson   File: plot_activities.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_history(input_filename, output_filename, width, height,
                 activities):
    """Generate an activity plot showing time spent in activity

    The horizontal axis is time (days), the vertical axis is minutes
    in activity (as determined by text match).

    """

    print(activities)
    activity = activities[0]    # TODO.  For the moment, just handle one.
    print(activity)
    tasks = gtd_load(input_filename, 'tasks')
    print('Dataframe loaded')
    x_dates = []
    y_minutes = []
    date_groups = tasks.groupby(['date'])
    for group_date, group_df in date_groups:
        count = group_df.loc[group_df.label.str.contains(activity)].time.count()
        x_dates.append(group_date)
        y_minutes.append(count)

    legend = []
    plt.plot(x_dates, y_minutes, '-r')
    legend.append(mpatches.Patch(color='g',
                                 label='Minutes using {activity}'.format(
                                     activity=activity)))

    plt.legend(handles=legend)
    plt.title('Minutes in {activity} by day'.format(
        activity=activity))
    fig = plt.gcf()
    fig.set_size_inches(width, height)
    plt.savefig(output_filename, dpi=100)
    print('Wrote {fn}'.format(fn=output_filename)) 
Example 18
Project: Human-Pose-Transfer   Author: budui   File: pose_utils.py    MIT License 5 votes vote down vote up
def draw_legend():
    handles = [mpatches.Patch(color=np.array(color) / 255.0, label=name) for color, name in zip(COLORS, LABELS)]
    plt.legend(handles=handles, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 
Example 19
Project: squeezenet-keras   Author: chasingbob   File: visual_callbacks.py    MIT License 5 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.epoch_count += 1
        self.val_acc.append(logs.get('val_acc'))
        self.acc.append(logs.get('acc'))
        self.loss.append(logs.get('loss'))
        self.val_loss.append(logs.get('val_loss'))
        epochs = [x for x in range(self.epoch_count)]

        count_subplots = 0
        
        if 'acc' in self.graphs:
            count_subplots += 1
            plt.subplot(self.num_subplots, 1, count_subplots)
            plt.title('Accuracy')
            #plt.axis([0,100,0,1])
            plt.plot(epochs, self.val_acc, color='r')
            plt.plot(epochs, self.acc, color='b')
            plt.ylabel('accuracy')

            red_patch = mpatches.Patch(color='red', label='Test')
            blue_patch = mpatches.Patch(color='blue', label='Train')

            plt.legend(handles=[red_patch, blue_patch], loc=4)

        if 'loss' in self.graphs:
            count_subplots += 1
            plt.subplot(self.num_subplots, 1, count_subplots)
            plt.title('Loss')
            #plt.axis([0,100,0,5])
            plt.plot(epochs, self.val_loss, color='r')
            plt.plot(epochs, self.loss, color='b')
            plt.ylabel('loss')

            red_patch = mpatches.Patch(color='red', label='Test')
            blue_patch = mpatches.Patch(color='blue', label='Train')

            plt.legend(handles=[red_patch, blue_patch], loc=4)
        
        plt.draw()
        plt.pause(0.001) 
Example 20
Project: ble5-nrf52-mac   Author: tomasero   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'Return a list of `~.patches.Patch` instances in the legend.'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 21
Project: racetrack   Author: ondrejba   File: environment.py    MIT License 5 votes vote down vote up
def show_racetrack(self, save_path=None, show_legend=True):
    """
    Show the racetrack with labels.
    https://stackoverflow.com/questions/25482876/how-to-add-legend-to-imshow-in-matplotlib
    :param save_path:     Where to save the figure.
    :param show_legend:   Show legend.
    :return:              None.
    """

    im =  plt.imshow(self.racetrack)

    plt.axis("off")

    if show_legend:
      values = np.unique(self.racetrack.ravel())
      labels = {
        constants.START_VALUE: "start",
        constants.END_VALUE: "end",
        constants.TRACK_VALUE: "track",
        constants.GRASS_VALUE: "grass"
      }
      colors = [im.cmap(im.norm(value)) for value in values]
      patches = [mpatches.Patch(color=colors[i], label=labels[values[i]]) for i in range(len(values))]
      plt.legend(handles=patches, loc=4)

    if save_path is not None:
      plt.savefig(save_path, bbox_inches="tight")

    plt.show() 
Example 22
Project: racetrack   Author: ondrejba   File: agent.py    MIT License 5 votes vote down vote up
def show_sequence(self, sequence, save_path=None, show_legend=True):
    """
    Show positions visited in a sequence.
    :param sequence:        Sequence of tuples: (state, action, reward).
    :param save_path:       Where to save the plot.
    :param show_legend:     Show legend.
    :return:                None.
    """

    track = self.env.racetrack.copy()

    for item in sequence:
      state = item[0]
      track[state[0], state[1]] = 4

    im = plt.imshow(track)

    plt.axis("off")

    if show_legend:
      values = np.unique(track.ravel())
      labels = {
        constants.START_VALUE: "start",
        constants.END_VALUE: "end",
        constants.TRACK_VALUE: "track",
        constants.GRASS_VALUE: "grass",
        constants.AGENT_VALUE: "agent"
      }
      colors = [im.cmap(im.norm(value)) for value in values]
      patches = [mpatches.Patch(color=colors[i], label=labels[values[i]]) for i in range(len(values))]
      plt.legend(handles=patches, loc=4)

    if save_path is not None:
      plt.savefig(save_path, bbox_inches="tight")

    plt.show() 
Example 23
Project: reinforcement_learning   Author: andreweskeclarke   File: runner.py    MIT License 5 votes vote down vote up
def main():
    print("Start sim")
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('settings', help='Location of the settings yaml file for the desired simulation')
    args = parser.parse_args()

    with open(args.settings, 'r') as stream:
        settings = yaml.load(stream)

    n_bandits = settings['n_bandits']
    n_runs = settings['n_runs']
    n_plays_per_run = settings['n_plays_per_run']
    patches = []
    for experiment in settings['experiments']:
        print(experiment)
        simulation = Sim(n_runs, n_plays_per_run,
                lambda _: eval(experiment['env_class'])(n_bandits, options=experiment['env_options']),
                lambda actions: eval(experiment['agent_class'])(actions, options=experiment['options']))
        simulation.run()
        simulation.plot(experiment['color'], experiment['label'])
        patches.append(mpatches.Patch(color=experiment['color'], label=experiment['label']))

    plt.axis([0,n_plays_per_run,0,1.05])
    plt.title("NBandits Reinforcement")
    plt.plot([0,n_plays_per_run],[0.9, 0.9], '--', color='g')
    plt.plot([0,n_plays_per_run],[0.95, 0.95], '--', color='b')

    plt.legend(handles=patches)
    plt.savefig('images/n_bandits_solutions.png')
    # plt.show() 
Example 24
Project: Computable   Author: ktraunmueller   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'return a list of patch instances in the legend'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 25
Project: Computable   Author: ktraunmueller   File: spines.py    MIT License 5 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        assert isinstance(path, matplotlib.path.Path)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 26
Project: neural-network-animation   Author: miloharper   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'return a list of patch instances in the legend'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 27
Project: everybody_dance_now_pytorch   Author: Lotayou   File: pose_utils.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def draw_legend():
    handles = [mpatches.Patch(color=np.array(color) / 255.0, label=name) for color, name in zip(COLORS, LABELS)]
    plt.legend(handles=handles, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 
Example 28
Project: alona   Author: oscar-franzen   File: cell.py    GNU General Public License v3.0 5 votes vote down vote up
def read_counts_per_cell_barplot(self):
        """ Generates a bar plot of read counts per cell. """
        if self.params['dataformat'] == 'raw':
            min_reads = self.params['minreads']
            cell_counts = self.data.sum(axis=0)
            plt.clf()
            figure(num=None, figsize=(5, 5))
            no_cells_remove = np.sum(np.array(sorted(cell_counts, reverse=True)) < \
                 min_reads)
            colors = [ORANGE]*(len(cell_counts)-no_cells_remove) + \
                     ['#999999']*no_cells_remove
            plt.bar(np.arange(len(cell_counts)), sorted(cell_counts, reverse=True),
                    color=colors)
            plt.ylabel('raw read counts')
            plt.xlabel('cells (sorted on highest to lowest)')
            plt.axhline(linewidth=1, color='r', y=min_reads)
            plt.legend(handles=[
                mpatches.Patch(color='#E69F00', label='Passed'),
                mpatches.Patch(color='#999999', label='Removed')
            ])
            plt.title('sequencing reads')
            if self.params['timestamp']:
                plt.figtext(0.05, 0, get_time(), size=5)
            plt.savefig(self.get_wd() + \
                OUTPUT['FILENAME_BARPLOT_RAW_READ_COUNTS'], bbox_inches='tight')
            plt.close() 
Example 29
Project: GraphicDesignPatternByPython   Author: Relph1119   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'Return a list of `~.patches.Patch` instances in the legend.'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 30
Project: python3_ios   Author: holzschu   File: legend.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_patches(self):
        'Return a list of `~.patches.Patch` instances in the legend.'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 31
Project: civilTools   Author: ebrahimraeyat   File: cross_section.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_mesh(self, nodes, elements, element_list, materials):
        """Watered down implementation of the CrossSection method to plot the
        finite element mesh, showing material properties."""

        (fig, ax) = plt.subplots()
        post.setup_plot(ax, True)

        # plot the mesh
        ax.triplot(nodes[:, 0], nodes[:, 1], elements[:, 0:3], lw=0.5,
                   color='black')

        color_array = []
        legend_list = []

        if materials is not None:
            # create an array of finite element colours
            for el in element_list:
                color_array.append(el.material.color)

            # create a list of unique material legend entries
            for (i, mat) in enumerate(materials):
                # if the material has not be entered yet
                if i == 0 or mat not in materials[0:i]:
                    # add the material colour and name to the legend list
                    legend_list.append(mpatches.Patch(color=mat.color,
                                                      label=mat.name))

            cmap = ListedColormap(color_array)  # custom colormap
            c = np.arange(len(color_array))  # indicies of elements

            # plot the mesh colours
            ax.tripcolor(nodes[:, 0], nodes[:, 1], elements[:, 0:3], c,
                         cmap=cmap)

            # display the legend
            ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),
                      handles=legend_list)

        # finish the plot
        post.finish_plot(ax, True, title='Finite Element Mesh') 
Example 32
Project: DLO-HiC-Tools   Author: GangCaoLab   File: infer_adapter.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_char_prob_stacked_bar(probs, start_pos=0):
    """ stacked bar plot of char probability """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Patch
    import pandas as pd

    base2color = OrderedDict({
        'A': '#b5ffb9', 
        'T': '#f9bc86',
        'C': '#a3acff',
        'G': '#ff9c9c',
        '-': 'grey',
    })
    
    r = [start_pos + i for i in range(len(probs))]

    raw_data = defaultdict(list)
    for p in probs:
        for b, v in p.items():
            raw_data[b].append(v)
    df = pd.DataFrame(raw_data)
    
    # plot
    fig, ax = plt.subplots()
    # Create Bars
    bottom = 0
    for b, color in base2color.items():
        ax.bar(r, df[b], bottom=bottom, color=color, edgecolor='white')
        bottom = (bottom + df[b]) if (bottom is not 0) else df[b]
    # modify
    plt.xlabel("Positions in mafft alignment result")
    plt.ylabel("Frequency of occurrence")
    plt.legend(handles=[Patch(color=c, label=l) for l,c in base2color.items()], loc='upper right')
    plt.xlim(start_pos-1, start_pos+len(probs))
    plt.ylim(0, 1)
    plt.tight_layout()
    return fig, ax 
Example 33
Project: ifp   Author: morris-frank   File: ifp_morris.py    GNU General Public License v3.0 5 votes vote down vote up
def apply_overlay(image, overlay, path, label=''):
    """
        Overlay overlay onto image and add label as text
        and save to path (full path with extension!)
    """
    fig = plt.figure(frameon=False)
    plt.imshow(image, interpolation='none')
    plt.imshow(overlay, cmap='plasma', alpha=0.7, interpolation='none')
    if label != '':
        red_patch = mpatches.Patch(color='yellow', label=label)
        plt.legend(handles=[red_patch])
    fig.savefig(path)
    plt.close(fig) 
Example 34
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'Return a list of `~.patches.Patch` instances in the legend.'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 35
Project: keras-visuals   Author: chasingbob   File: visual_callbacks.py    MIT License 5 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.epoch_count += 1
        self.val_acc.append(logs.get('val_acc'))
        self.acc.append(logs.get('acc'))
        self.loss.append(logs.get('loss'))
        self.val_loss.append(logs.get('val_loss'))
        epochs = [x for x in range(self.epoch_count)]

        count_subplots = 0
        
        if 'acc' in self.graphs:
            count_subplots += 1
            plt.subplot(self.num_subplots, 1, count_subplots)
            plt.title('Accuracy')
            #plt.axis([0,100,0,1])
            plt.plot(epochs, self.val_acc, color='r')
            plt.plot(epochs, self.acc, color='b')
            plt.ylabel('accuracy')

            red_patch = mpatches.Patch(color='red', label='Test')
            blue_patch = mpatches.Patch(color='blue', label='Train')

            plt.legend(handles=[red_patch, blue_patch], loc=4)

        if 'loss' in self.graphs:
            count_subplots += 1
            plt.subplot(self.num_subplots, 1, count_subplots)
            plt.title('Loss')
            #plt.axis([0,100,0,5])
            plt.plot(epochs, self.val_loss, color='r')
            plt.plot(epochs, self.loss, color='b')
            plt.ylabel('loss')

            red_patch = mpatches.Patch(color='red', label='Test')
            blue_patch = mpatches.Patch(color='blue', label='Train')

            plt.legend(handles=[red_patch, blue_patch], loc=4)
        
        plt.draw()
        plt.pause(0.001) 
Example 36
Project: Learn-Machine-Learning-in-3-Hours   Author: PacktPublishing   File: S3V5_example.py    MIT License 5 votes vote down vote up
def plot_legend(ax_in):

    """Add chicken and duck legend to scatter plot"""

    purple_patch = mpatches.Patch(color='red', label='Chicken')
    yellow_patch = mpatches.Patch(color='blue', label='Duck')
    ax_in.legend(handles=[purple_patch, yellow_patch]) 
Example 37
Project: Learn-Machine-Learning-in-3-Hours   Author: PacktPublishing   File: S3V3_example.py    MIT License 5 votes vote down vote up
def plot_legend(ax_in):

    """Add chicken and duck legend to scatter plot"""

    purple_patch = mpatches.Patch(color='purple', label='Chicken')
    yellow_patch = mpatches.Patch(color='yellow', label='Duck')
    ax_in.legend(handles=[purple_patch, yellow_patch]) 
Example 38
Project: Learn-Machine-Learning-in-3-Hours   Author: PacktPublishing   File: S3V4_example.py    MIT License 5 votes vote down vote up
def plot_legend(ax_in):

    """Add chicken and duck legend to scatter plot"""

    purple_patch = mpatches.Patch(color='red', label='Chicken')
    yellow_patch = mpatches.Patch(color='blue', label='Duck')
    ax_in.legend(handles=[purple_patch, yellow_patch]) 
Example 39
Project: Learn-Machine-Learning-in-3-Hours   Author: PacktPublishing   File: S4V5_example.py    MIT License 5 votes vote down vote up
def plot_legend(ax_in):

    """Add legend to scatter plot"""

    red_patch = mpatches.Patch(color='red', label='Labour')
    blue_patch = mpatches.Patch(color='blue', label='Conservative')
    green_patch = mpatches.Patch(color='green', label='Liberal Democrat')
    ax_in.legend(handles=[red_patch, blue_patch, green_patch]) 
Example 40
Project: Learn-Machine-Learning-in-3-Hours   Author: PacktPublishing   File: S4V3_example.py    MIT License 5 votes vote down vote up
def plot_legend(ax_in):

    """Add legend to scatter plot"""

    purple_patch = mpatches.Patch(color='purple', label='Labour')
    yellow_patch = mpatches.Patch(color='yellow', label='Conservative')
    green_patch = mpatches.Patch(color='green', label='Liberal Democrat')
    ax_in.legend(handles=[purple_patch, yellow_patch, green_patch]) 
Example 41
Project: linear_neuron   Author: uglyboxer   File: legend.py    MIT License 5 votes vote down vote up
def get_patches(self):
        'return a list of patch instances in the legend'
        return silent_list('Patch',
                           [h for h in self.legendHandles
                            if isinstance(h, Patch)]) 
Example 42
Project: PheKnowLator   Author: callahantiff   File: KGEmbeddingVisualizer.py    Apache License 2.0 4 votes vote down vote up
def main():

    # CONVERT EMBEDDINGS INTO PANDAS DATAFRAME
    # read in embedding file and re-generate node labels
    embedding_file = open('./resources/graphs/out.txt').readlines()[1:]
    node_labels = json.loads(open('./resources/graphs/KG_triples_ints_map.json').read())
    node_label_dict = {val: key for (key, val) in node_labels.items()}
    node_list = ['HP', 'CHEBI', 'VO', 'DOID', 'R-HSA', 'GO', 'geneid']

    # convert embeddings to df
    embeddings = processes_integer_labeled_embeddings(embedding_file, node_label_dict, node_list)
    embedding_data = pd.DataFrame(embeddings, columns=['node_type', 'node', 'embedding'])
    embedding_data.to_pickle('./resources/embeddings/PheKnowLator_embedding_dataframe')

    # DIMENSIONALITY REDUCTION
    x_reduced = TruncatedSVD(n_components=50, random_state=1).fit_transform(list(embedding_data['embeddings']))
    x_embedded = TSNE(n_components=2, random_state=1, verbose=True, perplexity=50.0).fit_transform(x_reduced)
    np.save('./resources/graphs/ALL_KG_res_tsne', x_embedded)

    # PLOT T-SNE
    # set up colors and legend labels
    colors = {'Diseases': '#009EFA',
              'Chemicals': 'indigo',
              'GO Concepts': '#F79862',
              'Genes': '#4fb783',
              'Pathways': 'orchid',
              'Phenotypes': '#A3B14B'}

    names = {key: key for key in colors.keys()}

    # create data frame to use for plotting data by node type
    df = pd.DataFrame(dict(x=x_embedded[:, 0], y=x_embedded[:, 1], group=list(embedding_data['node_type'])))
    groups = df.groupby('group')

    # create legend arguments
    dis = mpatches.Patch(color='#009EFA', label='Diseases')
    drg = mpatches.Patch(color='indigo', label='Drugs')
    go = mpatches.Patch(color='#F79862', label='GO Concepts')
    ge = mpatches.Patch(color='#4fb783', label='Genes')
    pat = mpatches.Patch(color='orchid', label='Pathways')
    phe = mpatches.Patch(color='#A3B14B', label='Phenotypes')

    legend_args = [[dis, drg, go, ge, pat, phe], 14, 'lower center', 3]
    title = 't-SNE: Biological Knowledge Graph'

    plots_embeddings(colors, names, groups, legend_args, 16, 100, title, 20) 
Example 43
Project: LaserTOF   Author: kyleuckert   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets] 
Example 44
Project: LaserTOF   Author: kyleuckert   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            msg = "'path' must be an instance of 'matplotlib.path.Path'"
            raise ValueError(msg)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 45
Project: LaserTOF   Author: kyleuckert   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          * a :class:`~matplotlib.patches.Patch` (or subclass) instance

          * a :class:`~matplotlib.path.Path` instance, in which case
             an optional :class:`~matplotlib.transforms.Transform`
             instance may be provided, which will be applied to the
             path before using it for clipping.

          * *None*, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to *None*.

        ACCEPTS: [ (:class:`~matplotlib.path.Path`,
        :class:`~matplotlib.transforms.Transform`) |
        :class:`~matplotlib.patches.Patch` | None ]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                               path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(
                    path.get_path(),
                    path.get_transform())
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            print(type(path), type(transform))
            raise TypeError("Invalid arguments to set_clip_path")
        # this may result in the callbacks being hit twice, but grantees they
        # will be hit at least once
        self.pchanged()
        self.stale = True 
Example 46
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets] 
Example 47
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 48
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

        - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
        - a :class:`~matplotlib.path.Path` instance, in which case a
          :class:`~matplotlib.transforms.Transform` instance, which will be
          applied to the path before using it for clipping, must be provided;
          or
        - ``None``, to remove a previously set clipping path.

        For efficiency, if the path happens to be an axis-aligned rectangle,
        this method will set the clipping box to the corresponding rectangle
        and set the clipping path to ``None``.

        ACCEPTS: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                               path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPatchPath(path)
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPatchPath):
            self._clippath = path
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            raise TypeError(
                "Invalid arguments to set_clip_path, of type {} and {}"
                .format(type(path).__name__, type(transform).__name__))
        # This may result in the callbacks being hit twice, but guarantees they
        # will be hit at least once.
        self.pchanged()
        self.stale = True 
Example 49
Project: gtd   Author: JeffAbrahamson   File: plot_history.py    GNU General Public License v2.0 4 votes vote down vote up
def plot_history(input_filename, output_filename, width, height,
                 color_host, color_host_class):
    """Generate an activity plot.

    The horizontal axis is time (days), the vertical axis is minutes
    spent at my computer per day.

    """
    tasks = gtd_load(input_filename, 'tasks')
    print('Dataframe loaded')
    # Express as a date rather than datetime so that we don't cut days
    # in two at the first recorded time each day.
    first_task_date = datetime.date.fromtimestamp(
        (min(tasks.datetime).to_datetime()
         - datetime.datetime.utcfromtimestamp(0)).total_seconds())
    tasks['day_index'] = tasks.apply(
        lambda row: (row['date'] - first_task_date).days, axis=1)
    print('Got days')
    tasks['day_of_month'] = tasks.apply(
        lambda row: row['datetime'].day, axis=1)
    print('Got first of month')

    x_points = tasks.day_index
    y_points = 1440 - tasks.minutes
    plt.xlim(0, max(x_points))
    plt.ylim(0, 1440)
    fig, ax = plt.subplots(1, 1)
    first_days = tasks.loc[tasks['day_of_month'] == 1]
    ax.set_xticks(sorted(first_days.day_index.unique()))
    ax.set_xticklabels(['{m}-{y}'.format(m=x.month, y=x.year)
                        for x in sorted(first_days.date.unique())])
    ax.set_yticks(np.linspace(0, 1440, 9))
    ax.set_yticklabels(['midnight', 21, 18, 15, 'noon', 9, 6, 3, 'midnight'])
    print('Scattering points...')
    if color_host or color_host_class:
        if color_host:
            column = 'hostname'
        else:
            column = 'host_class'
        names = tasks[column].unique()
        name_map = {names[index]: index
                    for index in range(len(names))}
        print(names)
        colors = cm.rainbow(np.linspace(0, 1, len(names)))
        legend = []
        for name in names:
            name_tasks = tasks.loc[tasks[column] == name]
            name_x_points = name_tasks.day_index
            name_y_points = 1440 - name_tasks.minutes
            name_color = colors[name_map[name]]
            plt.scatter(name_x_points, name_y_points, color=name_color,
                        s=1, edgecolors='none')
            legend.append(mpatches.Patch(color=name_color, label=name))
        plt.legend(handles=legend)
    else:
        plt.scatter(x_points, y_points, s=1, edgecolors='none')
    fig = plt.gcf()
    fig.set_size_inches(width, height)
    plt.savefig(output_filename, dpi=100)
    print('Wrote {fn}'.format(fn=output_filename)) 
Example 50
Project: gtd   Author: JeffAbrahamson   File: plot_pauses.py    GNU General Public License v2.0 4 votes vote down vote up
def plot_pauses(input_filename, output_filename, width, height,
                max_pause, sum_pauses):
    """Generate an activity plot showing pauses

    The horizontal axis is time (days), the vertical axis is minutes
    of pause (maximum or cumulative).

    """
    tasks = gtd_load(input_filename, 'tasks')
    print('Dataframe loaded')
    x_dates = []
    y_sums = []
    y_max = []
    date_groups = tasks.groupby(['date'])
    for group_date, group_df in date_groups:
        last_time = None
        max_interval = 0
        sum_interval = 0
        for row in group_df.sort_values(by=['time']).itertuples():
            this_time = int(row.time)
            if last_time is not None:
                interval_minutes = (this_time - last_time) / 60
                # Pauses should last at least a couple minutes,
                # otherwise maybe it's clock error.
                if 2 < interval_minutes and interval_minutes < max_pause:
                    sum_interval += interval_minutes
                    max_interval = max(interval_minutes, max_interval)
            last_time = this_time
        x_dates.append(group_date)
        y_sums.append(sum_interval)
        y_max.append(max_interval)

    legend = []
    plt.plot(x_dates, y_max, '-g')
    legend.append(mpatches.Patch(color='g', label='longest pause'))
    if sum_pauses:
        plt.plot(x_dates, y_sums, ':b')
        legend.append(mpatches.Patch(color='b', label='sum of pauses'))

    plt.legend(handles=legend)
    plt.title('Pauses by day (less than {mx} minutes)'.format(mx=max_pause))
    fig = plt.gcf()
    fig.set_size_inches(width, height)
    plt.savefig(output_filename, dpi=100)
    print('Wrote {fn}'.format(fn=output_filename)) 
Example 51
Project: active-evaluation   Author: arunchaganty   File: plot.py    MIT License 4 votes vote down vote up
def do_system_correlation(args):
    data = [json.loads(line) for line in open(args.input)]
    prompt, metric = args.data_prompt, args.data_metric
    task = first(key for key, values in PROMPTS.items() if prompt in values)
    systems = SYSTEMS[task]

    # Group by data by system.
    data = make_bias_table(data, prompt, metric, ["lr", "ur"])

    plt.rc("font", size=16)
    plt.rc("text", usetex=False)
    plt.rc("figure", figsize=(8,6))
    colors = cm.Dark2.colors[:len(systems)]

    def _thresh(y):
        return max(min(y, 1), -1)

    # 0. Plot the xy correlation curve.
    xy = np.array([[x, _thresh(y)] for system in systems for (x, *_), (y, *_) in [data[system]["default"]]])
    xlim = np.array([xy.T[0].min(), xy.T[0].max()])
    coeffs = np.polyfit(xy.T[0], xy.T[1], 1)
    plt.plot(xlim, xlim * coeffs[0] + coeffs[1], linestyle='--', linewidth=2, zorder=-1)

    # 1. Plot actual data points with error bars.
    xy = np.array([[x, y] for system in systems for (x, *_), (y, *_) in data[system].values()])
    xy_l = np.array([[x, y] for system in systems for (_, x, _), (_, y, _) in data[system].values()])
    xy_u = np.array([[x, y] for system in systems for (_, _, x), (_, _, y) in data[system].values()])
    plt.errorbar(xy.T[0], xy.T[1],
                 xerr=[(xy - xy_l).T[0], (xy_u - xy).T[0]],
                 yerr=[(xy - xy_l).T[1], (xy_u - xy).T[1]],
                 capsize=2, alpha=0.5, linestyle='', marker="", zorder=-1)

    # 2. Plot markers.
    xy = np.array([[x, y] for system in systems for (x, *_), (y, *_) in [data[system]["default"]]])
    xy_lr = np.array([[x, y] for system in systems for (x, *_), (y, *_) in [data[system]["lr"]]])
    xy_ur = np.array([[x, y] for system in systems for (x, *_), (y, *_) in [data[system]["ur"]]])

    plt.scatter(xy_lr.T[0], xy_lr.T[1], color=colors, marker=">")
    plt.scatter(xy_ur.T[0], xy_ur.T[1], color=colors, marker="^")
    plt.scatter(xy.T[0], xy.T[1], 100, c=colors, marker="o")
    plt.xlabel(r"Human judgement ({})".format(LABELS.get(prompt, prompt)))
    plt.ylabel(LABELS.get(metric, metric))

    if args.with_title:
        task = first(key for key, values in PROMPTS.items() if prompt in values)
        plt.title(r"System-level correlation on {}".format(
            LABELS.get(task, task),
            ), fontsize=14)

    plt.tight_layout()

    plt.legend(handles=[mp.Patch(color=colors[i], label=LABELS.get(system, system)) for i, system in enumerate(systems)])

    plt.savefig(args.output) 
Example 52
Project: Robotics-EIE3   Author: martinferianc   File: visualize_calibration.py    MIT License 4 votes vote down vote up
def draw_graph(logfile_path, logfile_name):
    data = pd.read_csv(logfile_path, sep="\t", header=None)
    fig = plt.figure(1)

    # set figure title
    plt.suptitle(logfile_name)

    ax1 = plt.subplot(211)
    ax1_line1 = plt.plot(data[0],data[2], "g")
    ax1_line2 = plt.plot(data[0],data[1], "b")
    ax1.set_title('Left motor', fontsize=12)
    plt.xlabel('Time [s]', fontsize=12)
    plt.ylabel('Angle [Radians]', fontsize=12)

    # create legends
    green_patch = mpatches.Patch(color='green', label='Actual angle')
    blue_patch = mpatches.Patch(color='blue', label='Reference angle')

    # place legends on the bottom right
    plt.legend(handles=[green_patch, blue_patch], loc=4)
 
    ax2 = plt.subplot(212)
    ax2_line1 = plt.plot(data[0],data[4], "g")
    ax2_line2 = plt.plot(data[0],data[3], "b")
    ax2.set_title('Right motor', fontsize=12)
    plt.xlabel('Time [s]', fontsize=12)
    plt.ylabel('Angle [Radians]', fontsize=12)

    # place legends on the bottom right
    plt.legend(handles=[green_patch, blue_patch], loc=4)

    # prevent overlapping
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])

    # save as png
    graph_path = './graphs/' + logfile_name + '.png'
    plt.savefig(graph_path, dpi=140)

    # do not show the plot, save instead
    # plt.show()

    # close figure to prevent adding different axes on the same plot
    plt.close() 
Example 53
Project: ble5-nrf52-mac   Author: tomasero   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets] 
Example 54
Project: ble5-nrf52-mac   Author: tomasero   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 55
Project: ble5-nrf52-mac   Author: tomasero   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

        - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
        - a :class:`~matplotlib.path.Path` instance, in which case a
          :class:`~matplotlib.transforms.Transform` instance, which will be
          applied to the path before using it for clipping, must be provided;
          or
        - ``None``, to remove a previously set clipping path.

        For efficiency, if the path happens to be an axis-aligned rectangle,
        this method will set the clipping box to the corresponding rectangle
        and set the clipping path to ``None``.

        ACCEPTS: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                               path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPatchPath(path)
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPatchPath):
            self._clippath = path
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            raise TypeError(
                "Invalid arguments to set_clip_path, of type {} and {}"
                .format(type(path).__name__, type(transform).__name__))
        # This may result in the callbacks being hit twice, but guarantees they
        # will be hit at least once.
        self.pchanged()
        self.stale = True 
Example 56
Project: Computable   Author: ktraunmueller   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines] 
Example 57
Project: Computable   Author: ktraunmueller   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          * a :class:`~matplotlib.patches.Patch` (or subclass) instance

          * a :class:`~matplotlib.path.Path` instance, in which case
             an optional :class:`~matplotlib.transforms.Transform`
             instance may be provided, which will be applied to the
             path before using it for clipping.

          * *None*, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to *None*.

        ACCEPTS: [ (:class:`~matplotlib.path.Path`,
        :class:`~matplotlib.transforms.Transform`) |
        :class:`~matplotlib.patches.Patch` | None ]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                              path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(
                    path.get_path(),
                    path.get_transform())
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            print(type(path), type(transform))
            raise TypeError("Invalid arguments to set_clip_path")

        self.pchanged() 
Example 58
Project: pynam   Author: hbp-unibi   File: binam_data_information_plot.py    GNU General Public License v3.0 4 votes vote down vote up
def plot(results, datasets):
    fig = plt.figure(figsize=(cm2inch(11.8), cm2inch(8)))
    ax = fig.add_subplot(111)
    t = results["t"]
    if len(datasets) == 0:
        datasets = range(len(results["info"]))
    legend_elems = []
    legend_labels = []
    for i in datasets:
        data = results["info"][i]
        title = results["title"][i].strip()
        if title in title_rewrites:
            title = title_rewrites[title]
        color = colors[i % len(colors)]
        i25, i75 = np.percentile(data, [25, 75], 0)
        ax.plot(t, np.median(data, 0), lw=1, color=color, zorder=1)
        ax.plot(t, data[np.argmax(np.max(data, 1))], ':', lw=0.5, color=color,
                zorder=2)
        ax.fill_between(t, i25, i75, facecolor=color, alpha=0.3, zorder=0, lw=0)
        ax.fill_between(t, np.min(data, 0), np.max(data, 0), facecolor=color,
                alpha=0.15, zorder=-1, lw=0)
        legend_elems.append(mlines.Line2D([], [], color=color, lw=1))
        legend_labels.append(title)

    refInfo = np.zeros(len(t))
    for i in xrange(1, len(t)):
        refInfo[i] = entropy.expected_entropy(t[i], results["n_bits"],
            results["n_ones"])
    plt.plot(t, refInfo, '--', color='k', lw=0.5, zorder=2)

#    color='#2e3436'
#    p1 = mlines.Line2D([], [], linestyle=':', color=color, lw=0.5)
#    p2 = mlines.Line2D([], [], linestyle='--', color='k', lw=0.5)
#    p3 = mpatches.Patch(color=color, alpha=0.3)
#    p4 = mpatches.Patch(color=color, alpha=0.15)
#    legend_elems = legend_elems + [p1, p2, p3, p4]
#    legend_labels = legend_labels + ["Trial with max. information",
#        "Expected information", "$25/75\%$-quantile", "Min./Max."]
#    legend_elems, legend_labels = reorder_legend(legend_elems, legend_labels)

    plt.legend(legend_elems, legend_labels, loc='lower center',
        bbox_to_anchor=(0.5, 1.05), ncol=2)

    ax.set_xlabel('Number of trained samples $N$')
    ax.set_ylabel('Information $I$ [Bit]')
    ax.set_xlim(np.min(t), np.max(t))
    plt.savefig(sys.argv[1] + ".pdf", format='pdf', bbox_inches='tight') 
Example 59
Project: citemap   Author: ai-se   File: expts_v3.py    The Unlicense 4 votes vote down vote up
def topic_evolution(venue=THE.permitted):
  print("TOPIC EVOLUTION for %s" % venue)
  miner, graph, lda_model, vocab = retrieve_graph_lda_data()
  paper_nodes = graph.get_paper_nodes(venue)
  topics_map = {}
  n_topics = lda_model.n_topics
  for paper_id, paper in paper_nodes.items():
    # if int(paper.venue) == 38:
    #   continue
    if int(paper.year) < 1992 or int(paper.year) > 2016: continue
    document = miner.documents[paper_id]
    year_topics = topics_map.get(paper.year, np.array([0] * n_topics))
    topics_map[paper.year] = np.add(year_topics, document.topics_count)
  yt_map = {}
  for year, t_count in topics_map.items():
    yt_map[year] = percent_sort(t_count)
  width = 0.6
  plts = []
  x_axis = np.arange(0, len(yt_map.keys()))
  y_offset = np.array([0] * len(yt_map.keys()))
  colors_dict = {}
  top_topic_count = 9
  # plt.figure(figsize=(8, 8))
  for index in range(top_topic_count):
    bar_val, color = [], []
    for year in sorted(yt_map.keys(), key=lambda x: int(x)):
      topic = yt_map[year][index]
      if topic[0] not in colors_dict:
        colors_dict[topic[0]] = get_color(topic[0])
      color.append(colors_dict[topic[0]])
      bar_val.append(topic[1])
    plts.append(plt.bar(x_axis, bar_val, width, color=color, bottom=y_offset))
    y_offset = np.add(y_offset, bar_val)
  plt.ylabel("Topic %")
  plt.xlabel("Year")
  plt.xticks(x_axis, [str(y)[2:] for y in sorted(yt_map.keys(), key=lambda x: int(x))], fontsize=9)
  plt.yticks(np.arange(0, 101, 10))
  plt.ylim([0, 101])
  # Legends
  patches = []
  topics = []
  for index, (topic, color) in enumerate(colors_dict.items()):
    patches.append(mpatches.Patch(color=color, label='Topic %s' % str(topic)))
    topics.append(get_topics()[topic])

  plt.legend(tuple(patches), tuple(topics), loc='upper center', bbox_to_anchor=(0.5, 1.14), ncol=5, fontsize=7,
             handlelength=0.7)
  plt.savefig("figs/v3/%s/topic_evolution/topic_evolution_%s.png" % (THE.permitted, venue), bbox_inches='tight')
  plt.clf() 
Example 60
Project: citemap   Author: ai-se   File: expts_v4.py    The Unlicense 4 votes vote down vote up
def topic_evolution(venue=THE.permitted, reverse=False):
  """
  Stacked bar-charts
  :param venue:
  :return:
  """
  print("TOPIC EVOLUTION for %s" % venue)
  miner, graph, lda_model, vocab = retrieve_graph_lda_data()
  paper_nodes = graph.get_paper_nodes(venue)
  topics_map = {}
  n_topics = lda_model.n_topics
  for paper_id, paper in paper_nodes.items():
    # if int(paper.venue) == 38:
    #   continue
    if int(paper.year) < 1992 or int(paper.year) > 2016: continue
    document = miner.documents[paper_id]
    year_topics = topics_map.get(paper.year, np.array([0] * n_topics))
    topics_map[paper.year] = np.add(year_topics, document.topics_count)
  yt_map = {}
  for year, t_count in topics_map.items():
    yt_map[year] = percent_sort(t_count)
  width = 0.6
  plts = []
  x_axis = np.arange(0, len(yt_map.keys()))
  y_offset = np.array([0] * len(yt_map.keys()))
  colors_dict = {}
  top_topic_count = 9
  plt.figure(figsize=(8, 6))
  for index in range(top_topic_count):
    if reverse:
      index = top_topic_count - index - 1
    bar_val, color = [], []
    for year in sorted(yt_map.keys(), key=lambda x: int(x)):
      topic = yt_map[year][index]
      if topic[0] not in colors_dict:
        colors_dict[topic[0]] = get_color(topic[0])
      # if reverse:
      #   bar_val.insert(0, topic[1])
      #   color.insert(0, colors_dict[topic[0]])
      # else:
      bar_val.append(topic[1])
      color.append(colors_dict[topic[0]])
    plts.append(plt.bar(x_axis, bar_val, width, color=color, bottom=y_offset))
    y_offset = np.add(y_offset, np.array(bar_val))
  plt.ylabel("Topic %")
  plt.xlabel("Year")
  plt.xticks(x_axis, [str(y)[2:] for y in sorted(yt_map.keys(), key=lambda x: int(x))], fontsize=9)
  plt.yticks(np.arange(0, 101, 10))
  plt.ylim([0, 101])
  # Legends
  patches = []
  topics = []
  for index, (topic, color) in enumerate(colors_dict.items()):
    patches.append(mpatches.Patch(color=color, label='Topic %s' % str(topic)))
    topics.append(get_topics()[topic])
  plt.legend(tuple(patches), tuple(topics), loc='upper center', bbox_to_anchor=(0.5, 1.14), ncol=5, fontsize=9,
             handlelength=0.7)
  plt.savefig("figs/%s/%s/topic_evolution/topic_evolution_%s.png" % (THE.version, THE.permitted, venue),
              bbox_inches='tight')
  plt.clf() 
Example 61
Project: citemap   Author: ai-se   File: ist.py    The Unlicense 4 votes vote down vote up
def topic_evolution():
  miner, graph, lda_model, vocab = get_graph_lda_data()
  paper_nodes = graph.paper_nodes
  topics_map = {}
  n_topics = lda_model.n_topics
  for paper_id, paper in paper_nodes.items():
    if int(paper.year) < 1993: continue
    document = miner.documents[paper_id]
    year_topics = topics_map.get(paper.year, np.array([0] * n_topics))
    topics_map[paper.year] = np.add(year_topics, document.topics_count)
  yt_map = {}
  for year, t_count in topics_map.items():
    yt_map[year] = percent_sort(t_count)
  width = 0.8
  plts = []
  x_axis = np.arange(1, len(yt_map.keys()) + 1)
  y_offset = np.array([0] * len(yt_map.keys()))
  colors_dict = {}
  top_topic_count = 9
  for index in range(top_topic_count):
    bar_val, color = [], []
    for year in sorted(yt_map.keys(), key=lambda x: int(x)):
      topic = yt_map[year][index]
      colors_dict[topic[0]] = get_color(topic[0])
      color.append(colors_dict[topic[0]])
      bar_val.append(topic[1])
    plts.append(plt.bar(x_axis, bar_val, width, color=color, bottom=y_offset))
    y_offset = np.add(y_offset, bar_val)
  plt.ylabel("Topic %")
  plt.xlabel("Year")
  plt.xticks(x_axis + width / 2, [str(y)[2:] for y in sorted(yt_map.keys(), key=lambda x: int(x))], fontsize=9)
  plt.yticks(np.arange(0, 101, 10))
  plt.ylim([0, 101])
  # Legends
  patches = []
  for index, (topic, color) in enumerate(colors_dict.items()):
    patches.append(mpatches.Patch(color=color, label='Topic %s' % str(topic)))
  plt.legend(tuple(patches), tuple(TOPICS), loc='upper center', bbox_to_anchor=(0.5, 1.14), ncol=6, fontsize=10,
             handlelength=0.7)
  plt.savefig("figs/v2/topic_evolution/topic_evolution_7.png")
  plt.clf()
  report(lda_model, vocab) 
Example 62
Project: citemap   Author: ai-se   File: icse.py    The Unlicense 4 votes vote down vote up
def pc_bias():
  def index_by_year(tups):
    y_comm = {}
    for tup in tups:
      comm = y_comm.get(tup[1], set())
      comm.add(tup[0])
      y_comm[tup[1]] = comm
    return y_comm

  legit_conferences = ["ICSE", "MSR", "FSE", "ASE"]
  colors = ['r', 'g', 'b', 'y']
  graph = cite_graph(GRAPH_CSV)
  width = 0.5
  space = 0.3
  p_conferences = graph.get_papers_by_venue()
  p_committees = graph.get_committee_by_conference()
  max_len = 21
  low = 1
  high = max_len * (len(legit_conferences)*width + space) + 1
  delta = (high - low)/max_len
  x_axis = np.arange(low, high, delta)
  x_ticks = np.arange(1993, 1993+max_len)
  conf_index = 0
  patches = []
  for conference in mysql.get_conferences():
    if conference.acronym not in legit_conferences: continue
    year_committees = index_by_year(p_committees[conference.id])
    year_papers = index_by_year(p_conferences[conference.id])
    year_scores = {}
    y_axis = []
    #x_axis = np.arange(1, len(year_committees.keys())+1)
    for year in sorted(year_committees.keys(), key=lambda y: int(y)):
      papers = year_papers.get(year,None)
      if papers is None:
        y_axis.append(0)
        continue
      committee = year_committees[year]
      comm_papers = 0
      non_comm_papers = 0
      for paper_id in papers:
        paper = graph.paper_nodes[paper_id]
        author_ids = set(paper.author_ids.strip().split(","))
        if author_ids.intersection(committee):
          comm_papers += 1
        else:
          non_comm_papers += 1
      year_scores[year] = (comm_papers, non_comm_papers)
      percent = 0 if not comm_papers else comm_papers*100/(comm_papers+non_comm_papers)
      y_axis.append(percent)
    y_axis = np.lib.pad(y_axis, (max_len-len(y_axis), 0), 'constant', constant_values=0)
    plt.bar(x_axis+conf_index*width, y_axis, width=width, color=colors[conf_index])
    patches.append(mpatches.Patch(color=colors[conf_index], label=conference.acronym))
    conf_index += 1
  plt.xlabel("Year")
  plt.ylabel("% of papers by PC")
  plt.xticks(x_axis + len(legit_conferences)*width/2, [str(y)[2:] for y in x_ticks])
  #plt.yticks(np.arange(0, 100, 10))
  #plt.title(conference.acronym)
  plt.legend(handles=patches, loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=len(legit_conferences), fontsize=7)
  plt.savefig("figs/pc/pc.png")
  plt.clf() 
Example 63
Project: citemap   Author: ai-se   File: icse.py    The Unlicense 4 votes vote down vote up
def topic_evolution():
  graph = cite_graph(GRAPH_CSV)
  miner = Miner(graph)
  lda_model, vocab = miner.lda(7, n_iter=100, alpha=0.847433736937, beta=0.763774618977)
  paper_nodes = graph.paper_nodes
  topics_map = {}
  n_topics = lda_model.n_topics
  for paper_id, paper in paper_nodes.items():
    document = miner.documents[paper_id]
    year_topics = topics_map.get(paper.year, np.array([0]*n_topics))
    topics_map[paper.year] = np.add(year_topics, document.topics_count)
  yt_map = {}
  for year, t_count in topics_map.items():
    yt_map[year] = percent_sort(t_count)
  width = 0.8
  plts = []
  x_axis = np.arange(1, len(yt_map.keys()) + 1)
  # x_axis = [c.acronym for c in mysql.get_conferences()]
  y_offset = np.array([0] * len(yt_map.keys()))
  colors_dict = {}
  TOP_TOPIC_COUNT = 7
  for index in range(TOP_TOPIC_COUNT):
    bar_val, color = [], []
    for year in sorted(yt_map.keys(), key=lambda x: int(x)):
      topic = yt_map[year][index]
      colors_dict[topic[0]] = get_color(topic[0])
      color.append(colors_dict[topic[0]])
      bar_val.append(topic[1])
    plts.append(plt.bar(x_axis, bar_val, width, color=color, bottom=y_offset))
    y_offset = np.add(y_offset, bar_val)
  plt.ylabel("Topic %")
  plt.xlabel("Year")
  plt.xticks(x_axis + width/2, [str(y)[2:] for y in sorted(yt_map.keys(), key=lambda x: int(x))])
  plt.yticks(np.arange(0, 101, 10))
  plt.ylim([0, 101])
  # Legends
  patches = []
  squares = []
  names = []
  t_names = ["Testing", "Applications", "Program Analysis", "Tools and Projects",
             "Defect Analysis", "Modeling", "Maintenance"]
  for index, (topic, color) in enumerate(colors_dict.items()):
    print(topic)
    patches.append(mpatches.Patch(color=color, label='Topic %s' % str(topic)))
    squares.append(plts[index][0])
    # names.append('Topic %s' % str(topic))
    # names.append(t_names[index])
  # plt.legend(handles=patches, loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=7, fontsize=9)
  plt.legend(tuple(patches), tuple(t_names), loc='upper center', bbox_to_anchor=(0.5, 1.14), ncol=4, fontsize=11, handlelength=0.7)
  plt.savefig("figs/topic_evolution/topic_evolution_7_gib.png")
  plt.clf()
  n_top_words = 10
  for index, topic_dist in enumerate(lda_model.topic_word_):
    topic_words = np.array(vocab)[np.argsort(topic_dist)][:-(n_top_words + 1):-1]
    print('Topic {}: {}'.format(index, ', '.join(topic_words))) 
Example 64
Project: neural-network-animation   Author: miloharper   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines] 
Example 65
Project: neural-network-animation   Author: miloharper   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        assert isinstance(path, matplotlib.path.Path)
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior two ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 66
Project: neural-network-animation   Author: miloharper   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          * a :class:`~matplotlib.patches.Patch` (or subclass) instance

          * a :class:`~matplotlib.path.Path` instance, in which case
             an optional :class:`~matplotlib.transforms.Transform`
             instance may be provided, which will be applied to the
             path before using it for clipping.

          * *None*, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to *None*.

        ACCEPTS: [ (:class:`~matplotlib.path.Path`,
        :class:`~matplotlib.transforms.Transform`) |
        :class:`~matplotlib.patches.Patch` | None ]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                              path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(
                    path.get_path(),
                    path.get_transform())
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            print(type(path), type(transform))
            raise TypeError("Invalid arguments to set_clip_path")

        self.pchanged() 
Example 67
Project: scanomatic   Author: Scan-o-Matic   File: phenotype_results.py    GNU General Public License v3.0 4 votes vote down vote up
def plot_phase_segmentation_in_steps(phenotyper, plate, position, plot_deriv=True, **kwargs):

    steps, model = get_curve_classification_in_steps(phenotyper, plate, position)
    plots = len(steps)

    if 'colors' in kwargs:
        colors = kwargs['colors']
    else:
        colors = PHASE_PLOTTING_COLORS

    if 'f' in kwargs:
        f = kwargs['f']
        del kwargs['f']
        f.clf()
    else:
        f = plt.figure("curve_{0}_{1}_{2}_segmentation_steps".format(plate, *position))

    legend_space = 2
    cols = int(np.ceil(np.sqrt(plots + legend_space)))
    rows = int(np.ceil(float(plots + legend_space) / cols))

    for i in range(plots):
        ax = f.add_subplot(rows, cols, i + 1)
        ax.set_title("Step {0}".format(i))
        plot_phases_from_data(model.times, model.log2_curve, steps[i], ax=ax, f=f,
                              deriv=model.dydt if plot_deriv else None,
                              plot_legend=False, set_labels=i==0,
                              **kwargs)

    ax = f.add_subplot(rows, cols, plots + 1)
    ax.axis("off")

    legend = []
    for phase in CurvePhases:
        if phase is CurvePhases.Multiple:
            continue

        legend.append(mpatches.Patch(color=colors[phase], label=re.sub(r'([a-z])([A-Z])', r'\1 \2', phase.name)))

    plt.legend(handles=legend, loc='center', fontsize='small',
               markerscale=0.66, ncol=2, bbox_to_anchor=(0., 0., 2., 1.), borderaxespad=0)

    f.tight_layout(h_pad=0.01, w_pad=0.01)

    return f 
Example 68
Project: GraphicDesignPatternByPython   Author: Relph1119   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets] 
Example 69
Project: GraphicDesignPatternByPython   Author: Relph1119   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 70
Project: GraphicDesignPatternByPython   Author: Relph1119   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

        - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
        - a :class:`~matplotlib.path.Path` instance, in which case a
          :class:`~matplotlib.transforms.Transform` instance, which will be
          applied to the path before using it for clipping, must be provided;
          or
        - ``None``, to remove a previously set clipping path.

        For efficiency, if the path happens to be an axis-aligned rectangle,
        this method will set the clipping box to the corresponding rectangle
        and set the clipping path to ``None``.

        ACCEPTS: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                               path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPatchPath(path)
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPatchPath):
            self._clippath = path
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            raise TypeError(
                "Invalid arguments to set_clip_path, of type {} and {}"
                .format(type(path).__name__, type(transform).__name__))
        # This may result in the callbacks being hit twice, but guarantees they
        # will be hit at least once.
        self.pchanged()
        self.stale = True 
Example 71
Project: 2016.2-SME_UnB   Author: fga-eps-mds   File: views.py    MIT License 4 votes vote down vote up
def create_graphic(path, array_date, array_dateb,
                   array_datec, array_data, label):
    title = _('Monitoring') + ' ' + label

    fig = Figure()

    ax = fig.add_subplot(111)
    bx = fig.add_subplot(111)
    cx = fig.add_subplot(111)
    x = []
    y = []
    yb = []
    yc = []
    xb = []
    xc = []

    for i in range(len(array_data)):
        x.append(array_data[i])
        y.append(array_date[i])
        xb.append(array_data[i])
        xc.append(array_data[i])
        yb.append(array_dateb[i])
        yc.append(array_datec[i])

    ax.plot_date(x, y, '-')
    bx.plot_date(xb, yb, '-')
    cx.plot_date(xc, yc, '-')

    patch1 = mpatches.Patch(color='blue', label=_('Phase 1'))
    patch2 = mpatches.Patch(color='green', label=_('Phase 2'))
    patch3 = mpatches.Patch(color='red', label=_('Phase 3'))

    z = [patch1, patch2, patch3]

    cx.legend(handles=z, loc=1)

    ax.set_title(title)
    ax.set_xlabel(_('Date'))
    ax.set_ylabel(label)
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas = FigureCanvas(fig)

    fig.savefig(path)

    return path 
Example 72
Project: python3_ios   Author: holzschu   File: legend.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets] 
Example 73
Project: python3_ios   Author: holzschu   File: spines.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super().__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 74
Project: RegRCNN   Author: MIC-DKFZ   File: plotting.py    Apache License 2.0 4 votes vote down vote up
def plot_wbc_n_missing(cf, df, outfile, fs=11, ax=None):
    """ WBC (weighted box clustering) has parameter n_missing, which shows how many boxes are missing per cluster.
        This function plots the average relative amount of missing boxes sorted by cluster score.
    :param cf: config.
    :param df: dataframe.
    :param outfile: path to save image under.
    :param fs: fontsize.
    :param ax: axes object.
    """

    bins = np.linspace(0., 1., 10)
    names = ["{:.1f}".format((bins[i]+(bins[i+1]-bins[i])/2.)*100) for i in range(len(bins)-1)]
    classes = df.pred_class.unique()
    colors = [cf.class_id2label[cl_id].color for cl_id in classes]

    binned_df = df.copy()
    binned_df.loc[:,"pred_score"] = pd.cut(binned_df["pred_score"], bins)

    close=False
    if ax is None:
        ax = plt.subplot()
        close=True
    width = 1 / (len(classes) + 1)
    group_positions = np.arange(len(names))
    legend_handles = []

    for ix, cl_id in enumerate(classes):
        cl_df = binned_df[binned_df.pred_class==cl_id].groupby("pred_score").agg({"cluster_n_missing": 'mean'})
        ax.bar(group_positions + ix * width, cl_df.cluster_n_missing.values, width=width, color=colors[ix],
                       alpha=0.4 + ix / 2 / len(classes), edgecolor=colors[ix])
        legend_handles.append(mpatches.Patch(color=colors[ix], label=cf.class_dict[cl_id]))

    title = "Fold {} WBC Missing Preds\nAverage over scores and classes: {:.1f}%".format(cf.fold, df.cluster_n_missing.mean())
    ax.set_title(title, fontsize=fs)
    ax.legend(handles=legend_handles, title="Class", loc="best", fontsize=fs, title_fontsize=fs)
    ax.set_xticks(group_positions + (len(classes) - 1) * width / 2)
    # ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.1f}')) THIS WONT WORK... no clue!
    ax.set_xticklabels(names)
    ax.tick_params(axis='both', which='major', labelsize=fs)
    ax.tick_params(axis='both', which='minor', labelsize=fs)

    ax.set_axisbelow(True)
    ax.grid()
    ax.set_ylabel(r"Average Missing Preds per Cluster (%)", fontsize=fs)
    ax.set_xlabel("Prediction Score", fontsize=fs)

    if close:
        if cf.server_env:
            IO_safe(plt.savefig, fname=outfile, _raise=False)
        else:
            plt.savefig(outfile)
        plt.close() 
Example 75
Project: RegRCNN   Author: MIC-DKFZ   File: plotting.py    Apache License 2.0 4 votes vote down vote up
def plot_fold_stats(cf, df, labels=None, out_file=None, ax=None):
    """ Similar as plot_data_stats but per single cross-val fold.
    :param cf: configs obj
    :param df: pandas dataframe
    :param out_file: path to save fig in
    """
    names = df.columns
    splits = df.index
    if labels is not None:
        colors = [label.color for name in names for label in labels if label.name==name]
    else:
        colors = [cf.color_palette[ix%len(cf.color_palette)] for ix in range(len(names))]
    #patterns = ('/', '\\', '*', 'O', '.', '-', '+', 'x',  'o')
    #patterns = tuple([patterns[ix%len(patterns)] for ix in range(len(splits))])
    if ax is None:
        ax = plt.subplot()
        return_ax = False
    else:
        return_ax = True
    width = 1/(len(names)+1)
    group_positions = np.arange(len(splits))
    legend_handles = []

    total_counts = [df.loc[split].sum() for split in splits]

    for ix, name in enumerate(names):
        rects = ax.bar(group_positions+ix*width, df.loc[:,name], width=width, color=colors[ix], alpha=0.9,
                       edgecolor=colors[ix])
        #for ix, bar in enumerate(rects):
            #bar.set_hatch(patterns[ix])
        labels = ["{:.0f}%".format(df.loc[split, name]/ total_counts[ii]*100) for ii, split in enumerate(splits)]
        label_bar(ax, rects, labels, [colors[ix]]*len(group_positions))

        legend_handles.append(mpatches.Patch(color=colors[ix] ,alpha=0.9, label=name))

    title= "Fold {} RoI-Target Balances\nTotal #RoIs: {}".format(cf.fold,
                 int(df.values.sum()))
    plt.title(title)
    ax.legend(handles=legend_handles)
    ax.set_xticks(group_positions + (len(names)-1)*width/2)
    ax.set_xticklabels(splits, rotation="vertical" if len(splits)>2 else None, size=12)
    ax.set_axisbelow(True)
    ax.grid()
    ax.set_ylabel(r"#RoIs")
    ax.set_xlabel("Set split")

    if out_file is not None:
        plt.savefig(out_file)
    if return_ax:
        return ax
    plt.close() 
Example 76
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []
        offsets = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        for handle in ax.collections:
            transform, transOffset, hoffsets, paths = handle._prepare_points()

            if len(hoffsets):
                for offset in transOffset.transform(hoffsets):
                    offsets.append(offset)

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines, offsets] 
Example 77
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: spines.py    MIT License 4 votes vote down vote up
def __init__(self, axes, spine_type, path, **kwargs):
        """
        - *axes* : the Axes instance containing the spine
        - *spine_type* : a string specifying the spine type
        - *path* : the path instance used to draw the spine

        Valid kwargs are:
        %(Patch)s
        """
        super(Spine, self).__init__(**kwargs)
        self.axes = axes
        self.set_figure(self.axes.figure)
        self.spine_type = spine_type
        self.set_facecolor('none')
        self.set_edgecolor(rcParams['axes.edgecolor'])
        self.set_linewidth(rcParams['axes.linewidth'])
        self.set_capstyle('projecting')
        self.axis = None

        self.set_zorder(2.5)
        self.set_transform(self.axes.transData)  # default transform

        self._bounds = None  # default bounds
        self._smart_bounds = False

        # Defer initial position determination. (Not much support for
        # non-rectangular axes is currently implemented, and this lets
        # them pass through the spines machinery without errors.)
        self._position = None
        if not isinstance(path, matplotlib.path.Path):
            raise ValueError(
                "'path' must be an instance of 'matplotlib.path.Path'")
        self._path = path

        # To support drawing both linear and circular spines, this
        # class implements Patch behavior three ways. If
        # self._patch_type == 'line', behave like a mpatches.PathPatch
        # instance. If self._patch_type == 'circle', behave like a
        # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
        # a mpatches.Arc instance.
        self._patch_type = 'line'

        # Behavior copied from mpatches.Ellipse:
        # Note: This cannot be calculated until this is added to an Axes
        self._patch_transform = mtransforms.IdentityTransform() 
Example 78
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: artist.py    MIT License 4 votes vote down vote up
def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

        - a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
        - a :class:`~matplotlib.path.Path` instance, in which case a
          :class:`~matplotlib.transforms.Transform` instance, which will be
          applied to the path before using it for clipping, must be provided;
          or
        - ``None``, to remove a previously set clipping path.

        For efficiency, if the path happens to be an axis-aligned rectangle,
        this method will set the clipping box to the corresponding rectangle
        and set the clipping path to ``None``.

        ACCEPTS: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                               path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPatchPath(path)
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPatchPath):
            self._clippath = path
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            raise TypeError(
                "Invalid arguments to set_clip_path, of type {} and {}"
                .format(type(path).__name__, type(transform).__name__))
        # This may result in the callbacks being hit twice, but guarantees they
        # will be hit at least once.
        self.pchanged()
        self.stale = True 
Example 79
Project: debarcer   Author: oicr-gsi   File: generate_plots.py    MIT License 4 votes vote down vote up
def CreateAxReadDepth(columns, rows, position, figure, data, YLabel):
    
    '''
    (int, int, int, figure_object, list, str) -> ax_object
    
    :param columns: Number of columns
    :param rows: Number of rows
    :param position: Ax position in figure
    :param figure: Figure object opened for writing
    :param data: Values to be plotted
    :param YLabel: Y axis label
        
    Return a ax object in figure
    '''
    
    # create an ax instance in figure
    ax = figure.add_subplot(rows, columns, position)
    # plot density distribution of read depth
    n1, b1, p1 = ax.hist(data[0], bins=15, align='mid', color = '#00cccc', alpha=0.5)
    n2, b2, p2 = ax.hist(data[1], bins=b1, align='mid', color = '#ff66ff', alpha=0.5)
    
    # do not show lines around figure  
    ax.spines["top"].set_visible(False)    
    ax.spines["bottom"].set_visible(True)    
    ax.spines["right"].set_visible(False)    
    ax.spines["left"].set_visible(False)  
    # do not show ticks
    plt.tick_params(axis='both', which='both', bottom=True, top=False,
                    right=False, left=False, labelbottom=True, colors = 'black',
                    labelsize = 12, direction = 'out')  
    
    # set x ticks    
    XMax = max(data[0] + data[1])
    step = SetUpTicks(XMax)
    ax.set_xticks([i for i in np.arange(0, XMax + step, step)])
    ax.set_xlabel('Read depth', color = 'black',  size = 14, ha = 'center')    
    
    YMax = max(n1 + n2)
    step = SetUpTicks(YMax)
    ax.set_yticks([i for i in np.arange(0, YMax + 1, step)])
    # set up y axis label and grid
    ax.set_ylabel(YLabel, color = 'black',  size = 14, ha = 'center')
    
    # add a light grey horizontal grid to the plot, semi-transparent, 
    ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.4, linewidth = 0.4)  
    # hide these grids behind plot objects
    ax.set_axisbelow(True)
    
    # add space between axis and tick labels
    ax.yaxis.labelpad, ax.xaxis.labelpad = 18, 18
    
    # add legend
    legend_elements = []
    legend_elements.append(Patch(facecolor='#00cccc', edgecolor= '#00cccc', label='highest', alpha=1))
    legend_elements.append(Patch(facecolor='#ff66ff', edgecolor='#ff66ff', label='others', alpha=1))
    ax.legend(handles=legend_elements, frameon=False, ncol=2, prop={'size': 12}, 
              bbox_to_anchor=(0.4, 1.1), loc='upper left', borderaxespad=0.)
    return ax 
Example 80
Project: linear_neuron   Author: uglyboxer   File: legend.py    MIT License 4 votes vote down vote up
def _auto_legend_data(self):
        """
        Returns list of vertices and extents covered by the plot.

        Returns a two long list.

        First element is a list of (x, y) vertices (in
        display-coordinates) covered by all the lines and line
        collections, in the legend's handles.

        Second element is a list of bounding boxes for all the patches in
        the legend's handles.
        """
        # should always hold because function is only called internally
        assert self.isaxes

        ax = self.parent
        bboxes = []
        lines = []

        for handle in ax.lines:
            assert isinstance(handle, Line2D)
            path = handle.get_path()
            trans = handle.get_transform()
            tpath = trans.transform_path(path)
            lines.append(tpath)

        for handle in ax.patches:
            assert isinstance(handle, Patch)

            if isinstance(handle, Rectangle):
                transform = handle.get_data_transform()
                bboxes.append(handle.get_bbox().transformed(transform))
            else:
                transform = handle.get_transform()
                bboxes.append(handle.get_path().get_extents(transform))

        try:
            vertices = np.concatenate([l.vertices for l in lines])
        except ValueError:
            vertices = np.array([])

        return [vertices, bboxes, lines]