Python matplotlib.pyplot.Line2D() Examples

The following are 30 code examples of matplotlib.pyplot.Line2D(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: SimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show() 
Example #2
Source File: FilteredSimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show() 
Example #3
Source File: visualize.py    From Hands-on-Neuroevolution-with-Python with MIT License 6 votes vote down vote up
def _draw_maze_(maze_env, ax):
    """
    The function to draw maze environment
    Arguments:
        maze_env:   The maze environment configuration.
        ax:         The figure axis instance
    """
    # draw maze walls
    for wall in maze_env.walls:
        line = plt.Line2D((wall.a.x, wall.b.x), (wall.a.y, wall.b.y), lw=1.5)
        ax.add_line(line)

    # draw start point
    start_circle = plt.Circle((maze_env.agent.location.x, maze_env.agent.location.y), 
                                radius=2.5, facecolor=(0.6, 1.0, 0.6), edgecolor='w')
    ax.add_patch(start_circle)
    
    # draw exit point
    exit_circle = plt.Circle((maze_env.exit_point.x, maze_env.exit_point.y), 
                                radius=2.5, facecolor=(1.0, 0.2, 0.0), edgecolor='w')
    ax.add_patch(exit_circle) 
Example #4
Source File: plot.py    From seqc with GNU General Public License v2.0 6 votes vote down vote up
def add_legend_to_categorical_vector(
        colors: np.ndarray, labels, ax, loc='best',  # bbox_to_anchor=(0.98, 0.5),
        markerscale=0.75, **kwargs):
    """
    Add a legend to a plot where the color scale was set by discretizing a colormap.

    :param colors: np.ndarray, output of map_categorical_vector_to_cmap()
    :param labels: np.ndarray, category labels
    :param ax: axis on which the legend should be plotted
    :param kwargs: additional kwargs for legend
    :return: None
    """
    artists = []
    for c in colors:
        artists.append(plt.Line2D((0, 1), (0, 0), color=c, marker='o', linestyle=''))
    ax.legend(
        artists, labels, loc=loc, markerscale=markerscale,  # bbox_to_anchor=bbox_to_anchor,
        **kwargs) 
Example #5
Source File: visualize.py    From Hands-on-Neuroevolution-with-Python with MIT License 6 votes vote down vote up
def _draw_maze_(maze_env, ax):
    """
    The function to draw maze environment
    Arguments:
        maze_env:   The maze environment configuration.
        ax:         The figure axis instance
    """
    # draw maze walls
    for wall in maze_env.walls:
        line = plt.Line2D((wall.a.x, wall.b.x), (wall.a.y, wall.b.y), lw=1.5)
        ax.add_line(line)

    # draw start point
    start_circle = plt.Circle((maze_env.agent.location.x, maze_env.agent.location.y), 
                                radius=2.5, facecolor=(0.6, 1.0, 0.6), edgecolor='w')
    ax.add_patch(start_circle)
    
    # draw exit point
    exit_circle = plt.Circle((maze_env.exit_point.x, maze_env.exit_point.y), 
                                radius=2.5, facecolor=(1.0, 0.2, 0.0), edgecolor='w')
    ax.add_patch(exit_circle) 
Example #6
Source File: plotting.py    From OpenTDA with Apache License 2.0 6 votes vote down vote up
def drawComplex(data, ph, axes=[-6, 8, -6, 6]):
    plt.clf()
    plt.axis(axes)  # axes = [x1, x2, y1, y2]
    plt.scatter(data[:, 0], data[:, 1])  # plotting just for clarity
    for i, txt in enumerate(data):
        plt.annotate(i, (data[i][0] + 0.05, data[i][1]))  # add labels

    # add lines for edges
    for edge in [e for e in ph.ripsComplex if len(e) == 2]:
        # print(edge)
        pt1, pt2 = [data[pt] for pt in [n for n in edge]]
        # plt.gca().add_line(plt.Line2D(pt1,pt2))
        line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r')
        plt.gca().add_line(line)

    # add triangles
    for triangle in [t for t in ph.ripsComplex if len(t) == 3]:
        pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]]
        line = plt.Polygon([pt1, pt2, pt3], closed=False,
                           color="blue", alpha=0.3, fill=True, edgecolor=None)
        plt.gca().add_line(line)
    plt.show() 
Example #7
Source File: visualize.py    From Hands-on-Neuroevolution-with-Python with MIT License 6 votes vote down vote up
def _draw_maze_(maze_env, ax):
    """
    The function to draw maze environment
    Arguments:
        maze_env:   The maze environment configuration.
        ax:         The figure axis instance
    """
    # draw maze walls
    for wall in maze_env.walls:
        line = plt.Line2D((wall.a.x, wall.b.x), (wall.a.y, wall.b.y), lw=1.5)
        ax.add_line(line)

    # draw start point
    start_circle = plt.Circle((maze_env.agent.location.x, maze_env.agent.location.y), 
                                radius=2.5, facecolor=(0.6, 1.0, 0.6), edgecolor='w')
    ax.add_patch(start_circle)
    
    # draw exit point
    exit_circle = plt.Circle((maze_env.exit_point.x, maze_env.exit_point.y), 
                                radius=2.5, facecolor=(1.0, 0.2, 0.0), edgecolor='w')
    ax.add_patch(exit_circle) 
Example #8
Source File: pendulum.py    From kusanagi with MIT License 6 votes vote down vote up
def __init__(self, pendulum_plant, refresh_period=(1.0/240),
                 name='PendulumDraw'):
        super(PendulumDraw, self).__init__(pendulum_plant,
                                           refresh_period, name)
        l = self.plant.l
        m = self.plant.m

        self.mass_r = 0.05*np.sqrt(m)  # distance to corner of bounding box

        self.center_x = 0
        self.center_y = 0

        # initialize the patches to draw the pendulum
        self.pole_line = plt.Line2D((self.center_x, 0), (self.center_y, l),
                                    lw=2, c='r')
        self.mass_circle = plt.Circle((0, l), self.mass_r, fc='y') 
Example #9
Source File: plot.py    From AGFusion with MIT License 6 votes vote down vote up
def _draw_fusion_junction(self, junction_location):

        junction_location_norm = junction_location/float(self.normalize)*0.9

        self.ax.add_line(plt.Line2D(
            (
                self.offset+junction_location_norm,
                self.offset+junction_location_norm
            ),
            (0.15+self.vertical_offset, 0.2+self.vertical_offset),
            color='black'
            )
        )
        self.right_marker_text = self.ax.text(
            self.offset+junction_location_norm,
            0.05+self.vertical_offset,
            str(junction_location/1000),
            horizontalalignment='center',
            fontsize=self.fontsize
        ) 
Example #10
Source File: neural_network.py    From neural-network-animation with MIT License 5 votes vote down vote up
def draw(self):
        line = pyplot.Line2D((self.x1, self.x2), (self.y1, self.y2), lw=fabs(self.weight), color=get_synapse_colour(self.weight), zorder=1)
        outer_glow = pyplot.Line2D((self.x1, self.x2), (self.y1, self.y2), lw=(fabs(self.weight) * 2), color=get_synapse_colour(self.weight), zorder=2, alpha=self.signal * 0.4)
        pyplot.gca().add_line(line)
        pyplot.gca().add_line(outer_glow) 
Example #11
Source File: test_visualizations.py    From pyret with MIT License 5 votes vote down vote up
def test_psth():
    """Test plotting a PSTH."""
    spikes, _ = utils.create_default_fake_spikes()
    visualizations.psth(spikes, trial_length=5.0)
    line = plt.findobj(plt.gca(), plt.Line2D)[0]
    xdata, ydata = line.get_data()
    binsize = 0.01
    ntrials = 2
    assert xdata.size == (spikes.size / binsize) / ntrials, \
            'visualizations.psth did not use trial length correctly'
    assert ydata.max() == (1 / binsize), \
            'visualizations.psth did not correctly compute max spike rate' 
Example #12
Source File: test_visualizations.py    From pyret with MIT License 5 votes vote down vote up
def test_raster():
    """Test plotting a spike raster."""
    spikes, labels = utils.create_default_fake_spikes()
    visualizations.raster(spikes, labels)
    line = plt.findobj(plt.gca(), plt.Line2D)[0]
    assert np.all(line.get_xdata() == spikes), 'Spike times do not match'
    assert np.all(line.get_ydata() == labels), 'Spike labels do not match'

    # Verify exception raised when spikes and labels different length
    with pytest.raises(AssertionError):
        visualizations.raster(np.array((0, 1)), np.array((0, 1, 2))) 
Example #13
Source File: test_visualizations.py    From pyret with MIT License 5 votes vote down vote up
def test_temporal_filter():
    """Test plotting a temporal filter directly."""
    # Plot filter
    temporal_filter, _, _ = utils.create_default_fake_filter()
    time = np.arange(temporal_filter.size)
    visualizations.temporal(time, temporal_filter)

    # Verify data plotted correctly
    line = plt.findobj(plt.gca(), plt.Line2D)[0]
    assert np.all(line.get_xdata() == time), \
            'Time axis data is incorrect.'
    assert np.all(line.get_ydata() == temporal_filter), \
            'Temporal filter data is incorrect.'
    plt.close(plt.gcf()) 
Example #14
Source File: visualizations.py    From M-LOOP with MIT License 5 votes vote down vote up
def plot_cost_vs_run(self):
        '''
        Create a plot of the costs versus run number.
        '''
        global figure_counter, run_label, cost_label, legend_loc
        figure_counter += 1
        plt.figure(figure_counter)
        
        # Only plot points for which a cost was actually measured. This may not
        # be the case for all parameter sets if the optimization is still in
        # progress, or ended by a keyboard interupt, etc..
        in_numbers = self.in_numbers[:self.num_in_costs]
        in_costs = self.in_costs[:self.num_in_costs]
        in_uncers = self.in_uncers[:self.num_in_costs]
        cost_colors = self.cost_colors[:self.num_in_costs]
        
        plt.scatter(in_numbers, in_costs+in_uncers, marker='_', color='k')
        plt.scatter(in_numbers, in_costs-in_uncers, marker='_', color='k')
        plt.scatter(in_numbers, in_costs,marker='o', c=cost_colors, s=5*mpl.rcParams['lines.markersize'])
        plt.xlabel(run_label)
        plt.ylabel(cost_label)
        plt.title('Controller: Cost vs run number.')
        artists = []
        for ut in self.unique_types:
            artists.append(plt.Line2D((0,1),(0,0), color=_color_from_controller_name(ut), marker='o', linestyle=''))
        plt.legend(artists,self.unique_types,loc=legend_loc) 
Example #15
Source File: test_figure.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_add_artist(fig_test, fig_ref):
    fig_test.set_dpi(100)
    fig_ref.set_dpi(100)

    ax = fig_test.subplots()
    l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1')
    l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2')
    r1 = plt.Circle((20, 20), 100, transform=None, gid='C1')
    r2 = plt.Circle((.7, .5), .05, gid='C2')
    r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,
                    facecolor='crimson', gid='C3')
    for a in [l1, l2, r1, r2, r3]:
        fig_test.add_artist(a)
    l2.remove()

    ax2 = fig_ref.subplots()
    l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure,
                    gid='l1', zorder=21)
    r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20,
                    gid='C1')
    r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2',
                    zorder=20)
    r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,
                    facecolor='crimson', clip_on=False, zorder=20, gid='C3')
    for a in [l1, r1, r2, r3]:
        ax2.add_artist(a) 
Example #16
Source File: roipoly.py    From roipoly.py with Apache License 2.0 5 votes vote down vote up
def display_roi(self, **linekwargs):
        line = plt.Line2D(self.x + [self.x[0]], self.y + [self.y[0]],
                          color=self.color, **linekwargs)
        ax = plt.gca()
        ax.add_line(line)
        plt.draw() 
Example #17
Source File: demo.py    From tf_ctpn with MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5, text=False):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :8]
        score = dets[i, -1]

        ax.add_line(
            plt.Line2D([bbox[0], bbox[2], bbox[6], bbox[4], bbox[0]],
                       [bbox[1], bbox[3], bbox[7], bbox[5], bbox[1]],
                       color='red', linewidth=3)
        )

        if text:
            ax.text(bbox[0], bbox[1] - 2,
                    '{:s} {:.3f}'.format(class_name, score),
                    bbox=dict(facecolor='blue', alpha=0.5),
                    fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
    plt.show() 
Example #18
Source File: plot.py    From AGFusion with MIT License 5 votes vote down vote up
def _draw_main_body(self, name_symbols, name_isoform):
        """
        main protein frame
        """

        length = (self.ensembl_transcript.end-self.ensembl_transcript.start)/float(self.normalize)*0.9

        self.ax.add_line(plt.Line2D(
            (
                self.offset,
                self.offset+length
            ),
            (0.5, 0.5),
            color='black'
            )
        )

        self.ax.text(
            0.5,
            0.9,
            name_symbols,
            horizontalalignment='center',
            fontsize=self.fontsize
        )
        self.ax.text(
            0.5,
            0.83,
            name_isoform,
            horizontalalignment='center',
            fontsize=self.fontsize-3
        ) 
Example #19
Source File: test_undulator_size.py    From xrt with MIT License 5 votes vote down vote up
def create_artists(self, legend, orig_handle,
                       x0, y0, width, height, fontsize, trans):
        l1 = plt.Line2D([x0+0.2*width], [0.5*height],
                        marker=orig_handle[0].get_paths()[0],
                        color=orig_handle[0].get_edgecolors()[0],
                        markerfacecolor='none')
        l2 = plt.Line2D([x0+0.8*width], [0.5*height],
                        marker=orig_handle[1].get_paths()[0],
                        color=orig_handle[1].get_edgecolors()[0],
                        markerfacecolor='none')
        return [l1, l2] 
Example #20
Source File: test_undulator_size.py    From xrt with MIT License 5 votes vote down vote up
def create_artists(self, legend, orig_handle,
                       x0, y0, width, height, fontsize, trans):
        l1 = plt.Line2D([x0, x0+width], [0.7*height, 0.7*height],
                        linestyle=orig_handle[0].get_linestyle(),
                        color=orig_handle[0].get_color())
        l2 = plt.Line2D([x0, x0+width], [0.3*height, 0.3*height],
                        linestyle=orig_handle[1].get_linestyle(),
                        color=orig_handle[1].get_color())
        return [l1, l2] 
Example #21
Source File: example.py    From gmm-torch with MIT License 5 votes vote down vote up
def plot(data, y):
    n = y.shape[0]

    fig, ax = plt.subplots(1, 1, figsize=(1.61803398875*4, 4))
    ax.set_facecolor('#bbbbbb')
    ax.set_xlabel("Dimension 1")
    ax.set_ylabel("Dimension 2")

    # plot the locations of all data points ..
    for i, point in enumerate(data.data):
        if i <= n//2:
            # .. separating them by ground truth ..
            ax.scatter(*point, color="#000000", s=3, alpha=.75, zorder=n+i)
        else:
            ax.scatter(*point, color="#ffffff", s=3, alpha=.75, zorder=n+i)

        if y[i] == 0:
            # .. as well as their predicted class
            ax.scatter(*point, zorder=i, color="#dbe9ff", alpha=.6, edgecolors=colors[1])
        else:
            ax.scatter(*point, zorder=i, color="#ffdbdb", alpha=.6, edgecolors=colors[5])

    handles = [plt.Line2D([0], [0], color='w', lw=4, label='Ground Truth 1'),
        plt.Line2D([0], [0], color='black', lw=4, label='Ground Truth 2'),
        plt.Line2D([0], [0], color=colors[1], lw=4, label='Predicted 1'),
        plt.Line2D([0], [0], color=colors[5], lw=4, label='Predicted 2')]

    legend = ax.legend(loc="best", handles=handles)

    plt.tight_layout()
    plt.savefig("example.pdf") 
Example #22
Source File: plant.py    From kusanagi with MIT License 5 votes vote down vote up
def init_artists(self):
        plt.figure(self.name)
        self.lines = [plt.Line2D(self.t_labels, self.data[:, i],
                                 c=next(color_generator)[0])
                      for i in range(self.data.shape[1])]
        self.ax.set_aspect('auto', 'datalim')
        for line in self.lines:
            self.ax.add_line(line)
        self.previous_update_time = time() 
Example #23
Source File: cartpole.py    From kusanagi with MIT License 5 votes vote down vote up
def init_artists(self):
        plt.figure(self.name)
        # initialize the patches to draw the cartpole
        l = self.plant.l
        cart_xy = (self.center_x-0.5*self.cart_h,
                   self.center_y-0.125*self.cart_h)
        self.cart_rect = plt.Rectangle(cart_xy, self.cart_h,
                                       0.25*self.cart_h, facecolor='black')
        self.pole_line = plt.Line2D((self.center_x, 0), (self.center_y, l),
                                    lw=2, c='r')
        self.mass_circle = plt.Circle((0, l), self.mass_r, fc='y')
        self.ax.add_patch(self.cart_rect)
        self.ax.add_patch(self.mass_circle)
        self.ax.add_line(self.pole_line) 
Example #24
Source File: double_cartpole.py    From kusanagi with MIT License 5 votes vote down vote up
def __init__(self, double_cartpole_plant, refresh_period=(1.0/240),
                 name='DoubleCartpoleDraw'):
        super(DoubleCartpoleDraw, self).__init__(double_cartpole_plant,
                                                 refresh_period, name)
        m1 = self.plant.m1
        m2 = self.plant.m2
        M = self.plant.M
        l1 = self.plant.l1
        l2 = self.plant.l2

        self.body_h = 0.5*np.sqrt(m1)
        self.mass_r1 = 0.05*np.sqrt(m2)  # distance to corner of bounding box
        self.mass_r2 = 0.05*np.sqrt(M)   # distance to corner of bounding box

        self.center_x = 0
        self.center_y = 0

        # initialize the patches to draw the cartpole
        self.body_rect = plt.Rectangle((self.center_x - 0.5*self.body_h,
                                       self.center_y - 0.125*self.body_h),
                                       self.body_h, 0.25*self.body_h,
                                       facecolor='black')
        self.pole_line1 = plt.Line2D((self.center_x, 0),
                                     (self.center_y, l1), lw=2, c='r')
        self.mass_circle1 = plt.Circle((0, l1), self.mass_r1, fc='y')
        self.pole_line2 = plt.Line2D((self.center_x, 0),
                                     (l1, l2), lw=2, c='r')
        self.mass_circle2 = plt.Circle((0, l1+l2), self.mass_r2, fc='y') 
Example #25
Source File: test_figure.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_artist(fig_test, fig_ref):
    fig_test.set_dpi(100)
    fig_ref.set_dpi(100)

    ax = fig_test.subplots()
    l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1')
    l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2')
    r1 = plt.Circle((20, 20), 100, transform=None, gid='C1')
    r2 = plt.Circle((.7, .5), .05, gid='C2')
    r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,
                    facecolor='crimson', gid='C3')
    for a in [l1, l2, r1, r2, r3]:
        fig_test.add_artist(a)
    l2.remove()

    ax2 = fig_ref.subplots()
    l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure,
                    gid='l1', zorder=21)
    r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20,
                    gid='C1')
    r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2',
                    zorder=20)
    r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,
                    facecolor='crimson', clip_on=False, zorder=20, gid='C3')
    for a in [l1, r1, r2, r3]:
        ax2.add_artist(a) 
Example #26
Source File: main.py    From visualise-neural-network with MIT License 5 votes vote down vote up
def __line_between_two_neurons(self, neuron1, neuron2):
        angle = atan((neuron2.x - neuron1.x) / float(neuron2.y - neuron1.y))
        x_adjustment = neuron_radius * sin(angle)
        y_adjustment = neuron_radius * cos(angle)
        line = pyplot.Line2D((neuron1.x - x_adjustment, neuron2.x + x_adjustment), (neuron1.y - y_adjustment, neuron2.y + y_adjustment))
        pyplot.gca().add_line(line) 
Example #27
Source File: mplutil.py    From netharn with Apache License 2.0 4 votes vote down vote up
def make_legend_img(classname_to_rgb, dpi=96, shape=(200, 200), mode='line',
                    transparent=False):
    """
    Makes an image of a categorical legend

    CommandLine:
        python -m netharn.util.mplutil make_legend_img

    Example:
        >>> # xdoctest: +REQUIRES(module:kwplot)
        >>> import kwplot
        >>> classname_to_rgb = {
        >>>     'blue': kwplot.Color('blue').as01(),
        >>>     'red': kwplot.Color('red').as01(),
        >>> }
        >>> img = make_legend_img(classname_to_rgb)
        >>> # xdoctest: +REQUIRES(--show)
        >>> kwplot.autompl()
        >>> kwplot.imshow(img)
        >>> kwplot.show_if_requested()
    """
    import kwplot
    plt = kwplot.autoplt()

    def append_phantom_legend_label(label, color, type_='line', alpha=1.0, ax=None):
        if ax is None:
            ax = plt.gca()
        _phantom_legend_list = getattr(ax, '_phantom_legend_list', None)
        if _phantom_legend_list is None:
            _phantom_legend_list = []
            setattr(ax, '_phantom_legend_list', _phantom_legend_list)
        if type_ == 'line':
            phantom_actor = plt.Line2D((0, 0), (1, 1), color=color, label=label,
                                       alpha=alpha)
        else:
            phantom_actor = plt.Circle((0, 0), 1, fc=color, label=label,
                                       alpha=alpha)
        _phantom_legend_list.append(phantom_actor)

    fig = plt.figure(dpi=dpi)

    w, h = shape[1] / dpi, shape[0] / dpi
    fig.set_size_inches(w, h)

    ax = fig.add_subplot('111')
    for label, color in classname_to_rgb.items():
        append_phantom_legend_label(label, color, type_=mode, ax=ax)

    _phantom_legend_list = getattr(ax, '_phantom_legend_list', None)
    if _phantom_legend_list is None:
        _phantom_legend_list = []
        setattr(ax, '_phantom_legend_list', _phantom_legend_list)
    ax.legend(handles=_phantom_legend_list)
    ax.grid(False)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.axis('off')
    legend_img = render_figure_to_image(fig, dpi=dpi, transparent=transparent)
    plt.close(fig)
    return legend_img 
Example #28
Source File: poster_PyConES2019_ENversion.py    From scikit-extremes with MIT License 4 votes vote down vote up
def make_XKCD_guy(
    filename,
    x=.5,
    y=.85,
    radius=.1,
    quote=None,
    color='k',
    lw=5,
    xytext=(0, 20),
    arm="left"
    ):
    # Stolen from https://alimanfoo.github.io/2016/05/31/matplotlib-xkcd.html
    fig, ax = plt.subplots(figsize=(10, 15))
    ax.set_axis_off()

    # draw the head
    head = plt.Circle((x, y), radius=radius, edgecolor=color, lw=lw,
                      facecolor='none', zorder=10)
    ax.add_patch(head)
    # draw the body
    body = plt.Line2D([x, x], [y-radius, y-(radius * 4)], 
                      color=color, lw=lw, transform=ax.transAxes)
    ax.add_line(body)
    # draw the arms
    if arm == 'left':
        arm1 = plt.Line2D([x, x+(4*radius)], [y-(radius * 1.5), y-(radius)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm1)
        arm2 = plt.Line2D([x, x-(radius * .8)], [y-(radius * 1.5), y-(radius*5)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm2)
    if arm == "right":
        arm1 = plt.Line2D([x, x-(4*radius)], [y-(radius * 1.5), y-(radius)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm1)
        arm2 = plt.Line2D([x, x+(radius * .8)], [y-(radius * 1.5), y-(radius*5)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm2)
    # draw the legs
    leg1 = plt.Line2D([x, x+(radius)], [y-(radius * 4), y-(radius*8)], 
                      color=color, lw=lw, transform=ax.transAxes)
    ax.add_line(leg1)
    leg2 = plt.Line2D([x, x-(radius*.5)], [y-(radius * 4), y-(radius*8)], 
                      color=color, lw=lw, transform=ax.transAxes)
    ax.add_line(leg2)

    fig.savefig(filename, transparent=True, dpi=DPI)
    return fig 
Example #29
Source File: poster_PyConES2019_ESversion.py    From scikit-extremes with MIT License 4 votes vote down vote up
def make_XKCD_guy(
    filename,
    x=.5,
    y=.85,
    radius=.1,
    quote=None,
    color='k',
    lw=5,
    xytext=(0, 20),
    arm="left"
    ):
    # Stolen from https://alimanfoo.github.io/2016/05/31/matplotlib-xkcd.html
    fig, ax = plt.subplots(figsize=(10, 15))
    ax.set_axis_off()

    # draw the head
    head = plt.Circle((x, y), radius=radius, edgecolor=color, lw=lw,
                      facecolor='none', zorder=10)
    ax.add_patch(head)
    # draw the body
    body = plt.Line2D([x, x], [y-radius, y-(radius * 4)], 
                      color=color, lw=lw, transform=ax.transAxes)
    ax.add_line(body)
    # draw the arms
    if arm == 'left':
        arm1 = plt.Line2D([x, x+(4*radius)], [y-(radius * 1.5), y-(radius)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm1)
        arm2 = plt.Line2D([x, x-(radius * .8)], [y-(radius * 1.5), y-(radius*5)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm2)
    if arm == "right":
        arm1 = plt.Line2D([x, x-(4*radius)], [y-(radius * 1.5), y-(radius)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm1)
        arm2 = plt.Line2D([x, x+(radius * .8)], [y-(radius * 1.5), y-(radius*5)],
                          color=color, lw=lw, transform=ax.transAxes)
        ax.add_line(arm2)
    # draw the legs
    leg1 = plt.Line2D([x, x+(radius)], [y-(radius * 4), y-(radius*8)], 
                      color=color, lw=lw, transform=ax.transAxes)
    ax.add_line(leg1)
    leg2 = plt.Line2D([x, x-(radius*.5)], [y-(radius * 4), y-(radius*8)], 
                      color=color, lw=lw, transform=ax.transAxes)
    ax.add_line(leg2)

    fig.savefig(filename, transparent=True, dpi=DPI)
    return fig 
Example #30
Source File: TFGenetic.py    From TF-Genetic with MIT License 4 votes vote down vote up
def draw_neural_net(self, ax, left, right, bottom, top, layer_sizes):
			'''
			Draw a neural network cartoon using matplotilb.
			
			:usage:
					>>> fig = plt.figure(figsize=(12, 12))
					>>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2])
			
			:parameters:
					- ax : matplotlib.axes.AxesSubplot
							The axes on which to plot the cartoon (get e.g. by plt.gca())
					- left : float
							The center of the leftmost node(s) will be placed here
					- right : float
							The center of the rightmost node(s) will be placed here
					- bottom : float
							The center of the bottommost node(s) will be placed here
					- top : float
							The center of the topmost node(s) will be placed here
					- layer_sizes : list of int
							List of layer sizes, including input and output dimensionality
			'''

			n_layers = len(layer_sizes) + 1
			maxLayerSize = 0

			for layer_group in layer_sizes:
				layer_size = sum(map(lambda x: x[1], layer_group))
				maxLayerSize = max(maxLayerSize, layer_size)
			v_spacing = (top - bottom)/float(maxLayerSize)
			h_spacing = (right - left)/float(len(layer_sizes) - 1)

			# Nodes
			for layerIndex, layer_group in enumerate(layer_sizes):
				layer_size = sum(map(lambda x: x[1], layer_group))
				layer_top = v_spacing*(layer_size - 1)/2. + (top + bottom)/2.
				currentIndex = 0
				for functionIndex, (inputSize, outputSize) in enumerate(layer_group):

					if outputSize > 0:
						
						for nodeIndex in range(outputSize):
							circle = plt.Circle((layerIndex*h_spacing + left, layer_top - currentIndex*v_spacing), v_spacing/4.,
																	color=self.activationFunctionColors[functionIndex], ec='k', zorder=4)
							ax.add_artist(circle)
							currentIndex += 1
					else:
						# Null nodes, ignore and keep going 
						continue
							
			"""
			# Edges
			for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
					layer_top_a = v_spacing*(layer_size_a - 1)/2. + (top + bottom)/2.
					layer_top_b = v_spacing*(layer_size_b - 1)/2. + (top + bottom)/2.
					for m in xrange(layer_size_a):
							for o in xrange(layer_size_b):
									line = plt.Line2D([n*h_spacing + left, (n + 1)*h_spacing + left],
																		[layer_top_a - m*v_spacing, layer_top_b - o*v_spacing], c='k')
									ax.add_artist(line)
			"""