Python matplotlib.pyplot.Line2D() Examples

The following are code examples for showing how to use matplotlib.pyplot.Line2D(). 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: pyplis   Author: jgliss   File: dataset.py    GNU General Public License v3.0 6 votes vote down vote up
def show_current_img(self, filter_id, add_forms=False):
        """Plot current image.

        :param str filter_id: filter ID of image list (e.g. "on")
        """
        ax = self.current_image(filter_id).show_img()
        if add_forms:
            handles = []
            for k, v in six.iteritems(self.lines._forms):
                l = Line2D([v[0], v[2]], [v[1], v[3]], color="#00ff00",
                           label=k)
                handles.append(l)
                ax.add_artist(l)
            for k, v in six.iteritems(self.rects._forms):
                w, h = v[2] - v[0], v[3] - v[1]
                r = Rectangle((v[0], v[1]), w, h, ec="#00ff00", fc="none",
                              label=k)
                ax.add_patch(r)
                handles.append(r)
            ax.legend(handles=handles, loc='best', fancybox=True,
                      framealpha=0.5, fontsize=10).draggable()

        return ax
        # ax.draw() 
Example 2
Project: OpenTDA   Author: outlace   File: plotting.py    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 3
Project: OpenTDA   Author: outlace   File: SimplicialComplex.py    Apache License 2.0 6 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 4
Project: OpenTDA   Author: outlace   File: FilteredSimplicialComplex.py    Apache License 2.0 6 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 5
Project: kusanagi   Author: mcgillmrl   File: pendulum.py    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 6
Project: imview   Author: dshean   File: stack_view.py    MIT License 6 votes vote down vote up
def create_legend(ax, source, loc='lower left'):
    lines = []
    labels = []
    uniq_src = np.ma.unique(source)
    if uniq_src.size == 1 and (uniq_src[0] == 'Other' or uniq_src[0] == 'None'):
        pass
    else:
        #Should create unique markers for each source
        #marker = itertools.cycle(('o', 's', '*', '+', '.', '*')) 
        for i in np.ma.unique(source):
            alpha = 1.0
            if i in source_dict:
                marker = source_dict[i]['marker']
                if 'alpha' in source_dict[i]:
                    alpha = source_dict[i]['alpha']
                label = source_dict[i]['label']
            else:
                marker = 'o'
                #marker = markers.next()
                label = i
            lines.append(plt.Line2D(list(range(1)), list(range(1)), linewidth=None, linestyle='', color='k', marker=marker, alpha=alpha, markersize=ms, markerfacecolor='k'))
            labels.append(label)
        marker_key = plt.legend(lines, labels, ncol=2, numpoints=1, loc=loc, prop={'size':8})
        ax.add_artist(marker_key) 
Example 7
Project: Hands-on-Neuroevolution-with-Python   Author: PacktPublishing   File: visualize.py    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
Project: Hands-on-Neuroevolution-with-Python   Author: PacktPublishing   File: visualize.py    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 9
Project: Hands-on-Neuroevolution-with-Python   Author: PacktPublishing   File: visualize.py    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 10
Project: seqc   Author: ambrosejcarr   File: plot.py    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 11
Project: MCTS-T   Author: tmoer   File: toy.py    MIT License 5 votes vote down vote up
def __init__(self,hps):
        fontsize = 20
        self.fig,self.ax = plt.subplots(1,figsize=(8,8))
        self.ax.add_patch(patches.Circle((0,1), radius=0.05,color='k'))
        self.ax.text(0.07,1,'$s_0$',fontsize=fontsize)
        self.ax.add_patch(patches.Circle((-0.5,0), radius=0.05,color='k'))
        self.ax.text(-0.43,0,'$s_1$',fontsize=fontsize)
        self.ax.add_patch(patches.Circle((0.5,0), radius=0.05,color='k'))
        self.ax.text(0.57,0,'$s_2$',fontsize=fontsize)
        self.ax.add_patch(patches.Circle((-0.75,-1), radius=0.05,color='k'))
        self.ax.add_patch(patches.Circle((-0.25,-1), radius=0.05,color='k'))
        self.ax.add_patch(patches.Circle((0.25,-1), radius=0.05,color='k'))
        self.ax.add_patch(patches.Circle((0.75,-1), radius=0.05,color='k'))
        self.basestrings = ['$a_0$,\n$r=-1$','$a_1$,\n$r=1$','$a_0$,\n$r=4$','$a_1$,\n$r=1$','$a_0$,\n$r=1$','$a_0$,\n$r=0$']        
        counts = [[]]*6
        
        self.ax.add_line(plt.Line2D((0, -0.5), (1, 0), lw=2.5,color='k'))        
        counts[0] = self.ax.text(-0.58,0.5,' $a_0$\n$r=-1$',fontsize=fontsize)
        self.ax.add_line(plt.Line2D((0, 0.5), (1, 0), lw=2.5,color='k'))        
        counts[1] = self.ax.text(0.3,0.5,' $a_1$\n$r=1$',fontsize=fontsize)

        self.ax.add_line(plt.Line2D((-0.5, -0.75), (0, -1), lw=2.5,color='k'))        
        counts[2] = self.ax.text(-0.95,-0.5,' $a_0$\n$r=4$',fontsize=fontsize)
        self.ax.add_line(plt.Line2D((-0.5, -0.25), (0, -1), lw=2.5,color='k'))        
        counts[3] = self.ax.text(-0.33,-0.5,' $a_1$\n$r=1$',fontsize=fontsize)

        self.ax.add_line(plt.Line2D((0.5, 0.25), (0, -1), lw=2.5,color='k'))        
        counts[4] =self.ax.text(0.08,-0.5,' $a_0$\n$r=1$',fontsize=fontsize)
        self.ax.add_line(plt.Line2D((0.5, 0.75), (0, -1), lw=2.5,color='k'))        
        counts[5] = self.ax.text(0.67,-0.5,' $a_1$\n$r=0$',fontsize=fontsize)
        
        self.counts = counts
        self.ax.set_xlim([-1.25,1.25])
        self.ax.set_ylim([-1.25,1.25])
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)

        self.fig.canvas.draw()
        self.fig.savefig(hps.base_result_dir + 'domain',dpi=300) 
Example 12
Project: tf_ctpn   Author: Sanster   File: demo.py    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 13
Project: ble5-nrf52-mac   Author: tomasero   File: test_figure.py    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 14
Project: skultrafast   Author: Tillsten   File: dataset.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def trans_anisotropy(self, wls, symlog=True, ax=None, freq_unit="auto"):
        """
        Plots the anisotropy over time for given frequencies.
        Parameters
        ----------
        wls : list of floats
            Which frequencies are plotted.
        symlog : bool
            Use symlog scale
        ax : plt.Axes or None
            Matplotlib Axes, if `None`, defaults to `plt.gca()`.

        Returns
        -------
        : list of Line2D
            List with the line objects.

        """
        if ax is None:
            ax = plt.gca()
        ds = self.pol_ds
        tmp = self.freq_unit if freq_unit == "auto" else freq_unit
        is_nm = tmp == "nm"
        x = ds.wavelengths if is_nm else ds.wavenumbers
        if is_nm:
            ph.vis_mode()
        else:
            ph.ir_mode()
        l = []
        for i in wls:
            idx = dv.fi(x, i)
            pa, pe = ds.para.data[:, idx], ds.perp.data[:, idx]
            aniso = (pa - pe) / (2 * pe + pa)
            l += ax.plot(ds.para.t,
                         aniso,
                         label=ph.time_formatter(ds.t[idx], ph.time_unit))
        ph.lbl_trans(use_symlog=symlog)
        if symlog:
            ax.set_xscale("symlog")
        ax.set_xlim(-1)
        return l 
Example 15
Project: neural-network-animation   Author: miloharper   File: neural_network.py    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 16
Project: python3_ios   Author: holzschu   File: test_figure.py    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 17
Project: mousecam   Author: arnefmeyer   File: lineselector.py    GNU General Public License v3.0 5 votes vote down vote up
def release_event(self, ev):

        if self.xy_start is not None:

            if ev.xdata is not None and ev.ydata is not None:
                self.xy_stop = (ev.xdata, ev.ydata)
                print("stopping coordinates:", self.xy_stop)

                if self.line is not None:
                    self.line.remove()

                x1, y1 = self.xy_start
                x2, y2 = self.xy_stop
                self.line = plt.Line2D([x1, x2], [y1, y2], ls='-', lw=2,
                                       color='r')
                self.ax.add_line(self.line)

                fig = self.ax.figure
                fig.canvas.draw()
                fig.canvas.flush_events()

            else:
                self.xy_start = None
                self.xy_stop = None

        else:
            self.xy_start = None 
Example 18
Project: trust_slab   Author: karllark   File: plot_slab_quant_comp.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_full_comp(compname, dcompnames, args, good_angles, ax,
                   tagstr, dispstr,
                   fontsize=14, dsym='-', plegend=True, dustemis=False):

    # setup the plot
    
    #taus = ['1e-2','1e-1','1e0','1e1']
    #fig, ax = plt.subplots(nrows=1,ncols=2,figsize=(15,8))
    #tax = [ax[0,0],ax[0,1],ax[1,0],ax[1,1]]

    taus = ['1e0','1e1']
    tax = ax

    col = ['b','g','r','c','m','y','k']
    models = ['CRT','DART-ray','DIRTY','Hyperion','SKIRT',
              'TRADING','SOC']
    dcol = dict(zip(models, col))

    for k, cur_ax in enumerate(tax):
        pmodels = plot_indiv_comp(cur_ax, taus[k], good_angles, 
                                  tagstr, dispstr, 
                                  dcompnames[compname], dcol,
                                  dsym=dsym, dustemis=dustemis)
        if k == 0:
            save_pmodels = pmodels

    # models
    if plegend:
        arts = [plt.Line2D((0,1),(0,0), color=dcol[cmodel], linestyle='-') 
                for cmodel in save_pmodels]
        leg1 = tax[0].legend(arts,
                             save_pmodels,
                             fontsize=1.25*fontsize,
                             loc='upper left',
                             ncol=2)
        leg1.get_frame().set_linewidth(2)

    # make y-axis better
    tax[1].yaxis.tick_right()
    tax[1].yaxis.set_ticks_position('both')
    tax[1].yaxis.set_label_position("right") 
Example 19
Project: Bee_space   Author: hobrien   File: ParseSpec.py    MIT License 5 votes vote down vote up
def Hexagon(traces, outfile, resolution):
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    from pylab import savefig
    #print "making hexagon"
    if not outfile:
        outfile = 'scatter.png'
    colours = ['b', 'y', 'r', 'c', 'm', 'g']
    fig, ax = plt.subplots()
    legend_points = []
    legend_titles = []
    if len(traces['x'].keys()) > len(colours):
        sys.exit("only %i different sample IDs can be plotted" % len(colours))
    for sample_id in sorted(traces['x'].iterkeys()):
        colour = colours.pop(0)
        ax.scatter(x=list(traces['x'][sample_id]), y=list(traces['y'][sample_id]), c=colour, marker='o')
        legend_points.append(plt.Line2D([0],[0], linestyle="none", c=colour, marker = 'o'))
        legend_titles.append(sample_id)
    #ax.set_xlabel('UV')
    #ax.set_ylabel('Green')
    ax.legend(legend_points, 
              legend_titles, 
              numpoints = 1, 
              ncol=3,
              columnspacing=1,
              loc=9,
              frameon=0,
              borderpad=0,
              handlelength=0
            )
    lines = [[(0, 1), (-.866, .5)], 
         [(0, -1), (-.866, -.5)],
         [(0, 1), (.866, .5)],
         [(0, -1), (.866, -.5)],
         [(.866, .5), (.866, -.5)],
         [(-.866, .5), (-.866, -.5)]
        ]
    lc = LineCollection(lines, colors='black', linewidths=2)
    ax.add_collection(lc)
    ax.margins(0.1)
    savefig(outfile, dpi=resolution) 
Example 20
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_figure.py    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 21
Project: GanSeg   Author: Roulbac   File: visualization.py    MIT License 5 votes vote down vote up
def plot_grad_flow(self, named_layers, net_name='', win=None, env=None):
        ave_grads = []
        max_grads = []
        layers = []
        for layer_name, layer in named_layers.items():
            for n, p in layer.named_parameters():
                if(p.requires_grad and ("bias" not in n)):
                    layers.append(layer_name)
                    abs_grad = None
                    if p.grad is None:
                        abs_grad = torch.zeros(p.shape)
                    else:
                        abs_grad = p.grad.abs()
                    ave_grads.append(abs_grad.mean().item())
                    max_grads.append(abs_grad.max().item())
                    break
        fig, ax = plt.subplots()
        ax.bar(np.arange(len(max_grads)), max_grads,
               alpha=0.1, lw=1, color="c")
        ax.bar(np.arange(len(max_grads)), ave_grads,
               alpha=0.1, lw=1, color="b")
        ax.hlines(0, 0, len(ave_grads), lw=2, color="k")
        ax.set_xticks(range(0, len(ave_grads), 1))
        ax.set_xticklabels(layers, rotation='vertical', fontsize='small')
        ax.set_yscale('log')
        ax.set_xlabel("Layers")
        ax.set_ylabel("Gradient magnitude")
        ax.set_title('{} Gradient flow'.format(net_name))
        ax.grid(True)
        ax.legend([plt.Line2D([0], [0], color="c", lw=4),
                   plt.Line2D([0], [0], color="b", lw=4)], ['max-gradient', 'mean-gradient'])
        fig.tight_layout()
        self.plot_matplot(fig, win, env)
        plt.close(fig) 
Example 22
Project: kusanagi   Author: mcgillmrl   File: double_cartpole.py    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 23
Project: kusanagi   Author: mcgillmrl   File: cartpole.py    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
Project: kusanagi   Author: mcgillmrl   File: plant.py    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 25
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_figure.py    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 26
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_figure.py    GNU General Public License v3.0 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 27
Project: mimclib   Author: StochasticNumerics   File: plot.py    GNU General Public License v2.0 5 votes vote down vote up
def draw(self, renderer):
        import matplotlib.pylab as plt
        ax = self.get_axes()
        if self.flip:
            y = self._linspace(ax.get_ylim(), ax.get_yscale())
            self.set_xdata(self.fn(y))
            self.set_ydata(y)
        else:
            x = self._linspace(ax.get_xlim(), ax.get_xscale())
            self.set_xdata(x)
            self.set_ydata(self.fn(x))

        plt.Line2D.draw(self, renderer)
        self.set_xdata([])
        self.set_ydata([]) 
Example 28
Project: Norfolk_Groundwater_Model   Author: UVAdMIST   File: RMSE_comparison_chart_fcst.py    MIT License 5 votes vote down vote up
def add_line(ax, xpos, ypos):
    line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
                      transform=ax.transAxes, color='gray')
    line.set_clip_on(False)
    ax.add_line(line) 
Example 29
Project: Norfolk_Groundwater_Model   Author: UVAdMIST   File: performance_bar_chart.py    MIT License 5 votes vote down vote up
def add_line(ax, xpos, ypos):
    line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
                      transform=ax.transAxes, color='gray')
    line.set_clip_on(False)
    ax.add_line(line) 
Example 30
Project: Norfolk_Groundwater_Model   Author: UVAdMIST   File: RMSE_comparison_chart.py    MIT License 5 votes vote down vote up
def add_line(ax, xpos, ypos):
    line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
                      transform=ax.transAxes, color='gray')
    line.set_clip_on(False)
    ax.add_line(line) 
Example 31
Project: ransomware-detection-with-deep-learning   Author: srihari-humbarwadi   File: draw_nn.py    MIT License 5 votes vote down vote up
def draw_neural_net(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)
    v_spacing = (top - bottom)/float(max(layer_sizes))
    h_spacing = (right - left)/float(len(layer_sizes) - 1)
    # Nodes
    for n, layer_size in enumerate(layer_sizes):
        layer_top = v_spacing*(layer_size - 1)/2. + (top + bottom)/2.
        for m in range(layer_size):
            circle = plt.Circle((n*h_spacing + left, layer_top - m*v_spacing), v_spacing/4.,
                                color='w', ec='k', zorder=4)
            ax.add_artist(circle)
    # 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 range(layer_size_a):
            for o in range(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',linewidth=0.4)
                ax.add_artist(line) 
Example 32
Project: frequenpy   Author: tomasjuanlink   File: animation.py    GNU General Public License v3.0 5 votes vote down vote up
def _support(self, x_coordinate):
        return plt.Line2D(
            (x_coordinate, x_coordinate),
            (-WALL_HEIGHT, WALL_HEIGHT),
            lw=WALL_WIDTH,
            color=WALL_COLOR
        ) 
Example 33
Project: frequenpy   Author: tomasjuanlink   File: animation.py    GNU General Public License v3.0 5 votes vote down vote up
def _build_line_with_markers(self):
        X, Y = self._beaded_string.rest_position
        return plt.Line2D(
            X, Y,
            marker=LINE_MARKERTYPE,
            lw=LINE_WIDTH,
            markersize=LINE_MARKERSIZE,
            markerfacecolor=LINE_MARKERFACECOLOR,
            color=LINE_COLOR,
            markevery=slice(1, len(X) - 1, 1)
        ) 
Example 34
Project: frequenpy   Author: tomasjuanlink   File: animation.py    GNU General Public License v3.0 5 votes vote down vote up
def _build_line_without_markers(self):
        X, Y = self._beaded_string.rest_position
        return plt.Line2D(
            X, Y,
            lw=LINE_WIDTH,
            color=LINE_COLOR
        ) 
Example 35
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 4 votes vote down vote up
def grid_spacing_vs_n_inh_fraction(self, time, spacing=None, from_file=True):
        """
        Parameters
        ----------


        Returns
        -------
        """

        cc = general_utils.plotting.color_cycle_blue6[::-1]
        mc = general_utils.plotting.marker_cycle
        # n_excs = [280, 400, 1000, 2000]
        n_excs = [840, 1200, 3000, 6000]
        color_dict = {}
        marker_dict = {}
        for i, nexc in enumerate(n_excs):
            color_dict[nexc] = cc[i]
            marker_dict[nexc] = mc[i]
        # color_dict = {140: cc[0], 280: cc[1], 400: cc[2], 1000: cc[3], 2000: cc[4]}
        # marker_dict = {140: mc[0], 280: mc[1], 400: mc[2], 1000: mc[3], 2000: mc[4]}

        for psp in self.psps:
            fig = plt.gcf()
            fig.set_size_inches(5.5, 4.0)
            self.set_params_rawdata_computed(psp, set_sim_params=True)
            n_exc = self.params['exc']['number_per_dimension']
            n_inh = self.params['inh']['number_per_dimension']

            if spacing is None:
                spacing = self.spacing
            frame = self.time2frame(time, weight=True)
            output_rates = self.get_output_rates(frame, spacing, from_file,
                                squeeze=True)
            grid_spacing = general_utils.arrays.get_mean_inter_peak_distance(
                            output_rates, 2*radius, 5, 0.1)

            plt.plot(n_exc/n_inh, grid_spacing,
                            color=color_dict[n_exc[0]],
                            marker=marker_dict[n_exc[0]],
                            alpha=1.0,
                            linestyle='none', markeredgewidth=0.0, lw=1)

        # The legend
        padding = 0.7
        handles = [plt.Line2D((0,1),(0,0), color=color_dict[n], lw=2)
                    for n in n_excs]
        labels = [r'$N^E={0}$'.format(n)
                    for n in n_excs]
        plt.legend(handles, labels, bbox_to_anchor=(1,0), loc='lower right', borderpad=padding,
                    labelspacing=padding, handlelength=1.5)
        plt.margins(0.1) 
Example 36
Project: skultrafast   Author: Tillsten   File: dataset.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def trans_integrals(self,
                        *args,
                        symlog: bool = True,
                        norm=False,
                        ax=None,
                        **kwargs) -> typing.List[plt.Line2D]:
        """
        Plot the transients of integrated region. The integration will use np.trapz in
        wavenumber-space.

        Parameters
        ----------
        args : tuples of floats
            Tuple of wavenumbers determining the region to be integrated.
        symlog : bool
            If to use a symlog scale for the delay-time.
        norm : bool or float
            If `true`, normalize to transients. If it is a float, the transients are
            normalzied to value at the delaytime norm.
        ax : plt.Axes or None
            Takes a matplotlib axes. If none, it uses `plt.gca()` to get the
            current axes. The lines are plotted in this ax

        kwargs : Further arguments passed to plt.plot

        Returns
        -------
        list of Line2D
            List containing the plotted lines.
        """
        if ax is None:
            ax = plt.gca()
        ph.ir_mode()
        ds = self.dataset
        l = []
        for (a, b) in args:
            a, b = sorted([a, b])
            idx = (a < ds.wavenumbers) & (ds.wavenumbers < b)
            dat = np.trapz(-ds.data[:, idx], ds.wavenumbers[idx], axis=1)

            if norm is True:
                dat = np.sign(dat[np.argmax(abs(dat))]) * dat / abs(dat).max()
            elif norm is False:
                pass
            else:
                dat = dat / dat[ds.t_idx(norm)]
            l.extend(
                ax.plot(ds.t,
                        dat,
                        label=f"{a: .0f} cm-1 to {b: .0f}",
                        **kwargs))

        if symlog:
            ax.set_xscale("symlog", linthreshx=1.0)
        ph.lbl_trans(ax=ax, use_symlog=symlog)
        ax.legend(loc="best", ncol=2)
        ax.set_xlim(right=ds.t.max())
        ax.yaxis.set_tick_params(which="minor", left=True)
        return l 
Example 37
Project: skultrafast   Author: Tillsten   File: dataset.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def spec(self, *times, norm=False, ax=None, n_average=0, **kwargs):
        """
        Plot spectra at given times.

        Parameters
        ----------
        *times : list or ndarray
            List of the times where the spectra are plotted.
        norm : bool
            If true, each spectral will be normalized.
        ax : plt.Axis or None.
            Axis where the spectra are plotted. If none, the current axis will
            be used.
        n_average : int
            For noisy data it may be prefered to average multiple spectra
            together. This function plots the average of `n_average` spectra
            around the specific time-points.
        upsample : int
            If >1, upsample the spectrum using cubic interpolation.

        Returns
        -------
        tuple of (List of `Lines2D`)
            List containing the Line2D objects belonging to the spectra.
        """

        pa, pe = self.pol_ds.para, self.pol_ds.perp
        l1 = pa.plot.spec(*times,
                          norm=norm,
                          ax=ax,
                          n_average=n_average,
                          **self.para_ls,
                          **kwargs)
        l2 = pe.plot.spec(*times,
                          norm=norm,
                          ax=ax,
                          n_average=n_average,
                          **self.perp_ls,
                          **kwargs)
        dv.equal_color(l1, l2)
        self.lbl_spec(ax)
        return l1, l2 
Example 38
Project: Dee.py   Author: AliFlux   File: visualize_dee.py    MIT License 4 votes vote down vote up
def visualize(dee):
		
		# print this to see the nodes in each layer
		layer_sizes = np.concatenate(([np.shape(dee.X)[1]], dee.hiddenLayers, [dee.outputNodes]))
		
		# making the plot
		fig = plt.figure(figsize=(len(layer_sizes) * 2.4, np.max(layer_sizes) * 1.2))
		fig.clear()
		fig.set_tight_layout(False)
		ax = fig.gca()
		ax.margins(0.1)
		ax.axis('off')
		left, right, bottom, top = 0.1, 0.9, 0.3, 0.7
		
		v_spacing = (top - bottom)/float(max(layer_sizes))
		h_spacing = (right - left)/float(len(layer_sizes) - 1)
		
		# print this to see colors of each layer
		colors = np.concatenate((["#2ecc71"], ["#3498db"] * int(len(layer_sizes)-2), ["#e74c3c"]))
		
		# drawing nodes/neurons/circles of each layer
		for n, layer_size in enumerate(layer_sizes):
			layer_top = v_spacing*(layer_size - 1)/2. + (top + bottom)/2.
			for m in range(layer_size):
				ax.plot(n*h_spacing + left, layer_top - m*v_spacing,'o',color=colors[n],fillstyle='full',markersize=40, zorder=4)
				ax.plot(n*h_spacing + left, layer_top - m*v_spacing,'o',color='white',fillstyle='full',markersize=45, zorder=3)
		
		# drawing lines/synapses between nodes
		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.
			
			weights = dee.W[n]
			minWeight, maxWeight = np.min(weights), np.max(weights)
			
			for m in range(layer_size_a):
				for o in range(layer_size_b):
					lineWidth = (weights[m, o]-minWeight)/(maxWeight-minWeight) * 5
					line = plt.Line2D([n*h_spacing + left, (n + 1)*h_spacing + left],
									  [layer_top_a - m*v_spacing, layer_top_b - o*v_spacing], color='#778ca3', linewidth=lineWidth)
					ax.add_artist(line)
	
	# plots the result of the network in form of a 2D chart
	# based on http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/ 
Example 39
Project: trust_slab   Author: karllark   File: plot_slab_quant_comp_image.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_slice_all_taus(args, good_angles, waves, ax, dispstr,
                        fontsize=14, plegend=True, irwaves=False):

    # setup the plot
    taus = ['1e0','1e1']
    tax = ax

    col = ['b','g','r','c','m','y','k']
    models = ['CRT','DART-ray','DIRTY','Hyperion','SKIRT',
              'TRADING','SOC']
    dcol = dict(zip(models, col))

    for k, cur_ax in enumerate(tax):
        pmodels = plot_indiv_slice(cur_ax, taus[k], waves, good_angles, 
                                   dispstr,dcol, irwaves=irwaves)
        if k == 0:
            save_pmodels = pmodels

    # Create two custom legends (more compact)

    # models
    if plegend:
        arts = [plt.Line2D((0,1),(0,0), color=dcol[cmodel], linestyle='-') 
                for cmodel in save_pmodels]
        leg1 = tax[0].legend(arts,
                             save_pmodels,
                             fontsize=1.25*fontsize,
                             loc='upper left',
                             ncol=2)
        leg1.get_frame().set_linewidth(2)

    # Add the legend manually to the current Axes.
    #tax[0].add_artist(leg1)

    # waves
    if args.sto and not args.uvopt:
        arts = [plt.Line2D((0,1),(0,0), color='k', linestyle='-'),
                plt.Line2D((0,1),(0,0), color='k', linestyle='--'),
                plt.Line2D((0,1),(0,0), color='k', linestyle='-.')]
        labs = [r'$\lambda = '+waves[0]+'$',
                r'$\lambda = '+waves[1]+'$',
                r'$\lambda = '+waves[2]+'$']
    else:
        arts = [plt.Line2D((0,1),(0,0), color='k', linestyle='-'),
                plt.Line2D((0,1),(0,0), color='k', linestyle='--')]
        labs = [r'$\lambda = '+waves[0]+'$',
                r'$\lambda = '+waves[1]+'$']
        
    leg2 = tax[1].legend(arts, labs,
                         title='Y Slice',
                         fontsize=1.25*fontsize,
                         loc='upper center', 
                         bbox_to_anchor=(-0.05,0.97))
    leg2.get_title().set_fontsize(fontsize*1.5)
    leg2.get_frame().set_linewidth(2)

    # make y axis nice

    tax[1].yaxis.tick_right()
    tax[1].yaxis.set_ticks_position('both')
    tax[1].yaxis.set_label_position("right") 
Example 40
Project: Bee_space   Author: hobrien   File: ParseSpec.py    MIT License 4 votes vote down vote up
def RotatingPlot(traces, outfile, resolution):
    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    from pylab import savefig
    from subprocess import call
    from platform import system
    if not outfile:
        outfile = 'scatter.gif'
        
    colours = ['b', 'y', 'r', 'c', 'm', 'g']
    if len(traces) > len(colours):
        sys.exit("not enough colours available for plotting")
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    #ax.scatter(IrRed[2], IrRed[1], IrRed[0], c='b', marker='o')
    legend_points = []
    legend_titles = []
    for sample_id in traces['x'].keys():
        colour = colours.pop(0)
        ax.scatter(list(traces['b'][sample_id]), list(traces['g'][sample_id]), list(traces['uv'][sample_id]), c=colour, marker='o')
        legend_points.append(plt.Line2D([0],[0], linestyle="none", c=colour, marker = 'o'))
        legend_titles.append(sample_id)
    ax.set_xlabel('Blue')
    ax.set_ylabel('Green')
    ax.set_zlabel('UV')
    ax.legend(legend_points, 
              legend_titles, 
              numpoints = 1, 
              ncol=3,
              columnspacing=1,
              loc=9,
              frameon=0,
              borderpad=0,
              handlelength=0
            )

    for i in range(1, 361):
        ax.view_init(elev=45, azim=i)
        if i < 45:
            i += 360
        savefig("scatter_%03d.png" % i, dpi=resolution)
    if system() == 'Windows':
        convert = os.path.join(os.path.split(os.path.realpath(sys.argv[0]))[0], 'IMconvert.cmd')
        call([convert, "-delay", "10", "-loop", "0", "scatter_*.png", outfile])
    else:
        call(["convert", "-delay", "10", "-loop", "0", "scatter_*.png", outfile])
    for i in range(45, 405):
        os.remove("scatter_%03d.png" % i) 
Example 41
Project: synscapes-utils   Author: 7dlabs   File: visualize-synscape-metadata.py    MIT License 4 votes vote down vote up
def draw_3d():
    vehicle_to_sensor_xform = vehicle_to_sensor_transform(metadata)
    # Projection
    fx = metadata['camera']['intrinsic']['fx']
    fy = metadata['camera']['intrinsic']['fy']
    u0 = metadata['camera']['intrinsic']['u0']
    v0 = metadata['camera']['intrinsic']['v0']
    # Transform corner points to image space
    is_pts = {}
    for inst, box in bbox_data.items():
        # Cull
        occluded = metadata['instance']['occluded'][inst]
        if occluded > args.threshold / 100.0:
            continue
        # Vehicle coordinates
        vc = box['origin']
        # Add zero vector for origin offset
        box['o'] = (0, 0, 0)
        # Image coordinates
        is_pts[inst] = {
            name: vehicle_space_to_image_space(vec_sum(box['origin'], box[name]),
                                               vehicle_to_sensor_xform,
                                               fx, fy, u0, v0) \
            for name in ['o', 'x', 'y', 'z']
        }
    # Create lines
    lines = []
    for inst, box in is_pts.items():
        # Color
        class_idx = metadata['instance']['class'][inst]
        class_name = class_id_to_str[class_idx]
        color = tableau20[class_idx % len(tableau20)]
        # Vertices
        o = box['o']
        x = box['x']
        y = box['y']
        z = box['z']
        # Lines
        for tgt in [x, y, z]:
            verts_x = [o[0], tgt[0]]
            verts_y = [o[1], tgt[1]]
            line = plt.Line2D(verts_x, verts_y, c=color, lw=2)
            ax.add_line(line)
            # plt.scatter(verts_x, verts_y, c=(1, 1, 1))
        # Text
        plt.text(o[0] + 2, o[1] - 2, '{}'.format(class_name),
                 color=text_color, bbox=dict(facecolor=color, alpha=0.5))
        
    
# Script --- 
Example 42
Project: HackThe6ix   Author: Researchnix   File: visualization.py    MIT License 4 votes vote down vote up
def visualization():
    inter_x = []
    inter_y = []
    plt.axes()
    

    f = open('inter.txt', 'r')
    for line in f:
        line = line.split()
        inter_x.append(int(line[1]))
        inter_y.append(int(line[2]))
    f.close()


    #intersections (x0, y0)
    for i in range(0, len(inter_x)):
        circle = plt.Circle((inter_x[i], inter_y[i]), 0.5, fc='b')
        plt.gca().add_patch(circle)
    plt.axis('scaled')

    f = open('ori.txt', 'r')
    for line in f:
        line = line.split()
        for i in line:
            street = plt.Line2D((inter_x[int(line[0])], inter_x[int(i)]), (inter_y[int(line[0])], inter_y[int(i)]), lw=3.0)
            plt.gca().add_line(street)
    f.close()


    f = open('ori.txt','r')
    for line in f:
        line = line.split()
        for i in line:
            if inter_x[int(line[0])] == inter_x[int(i)]:
                if inter_y[int(line[0])] > inter_y[int(i)]:
                    plt.gca().add_patch(Rectangle((inter_x[int(line[0])]-0.25,inter_y[int(line[0])]-1),0.5,0.5,fc='r'))
                if inter_y[int(line[0])] < inter_y[int(i)]:
                    plt.gca().add_patch(Rectangle((inter_x[int(line[0])]-0.25,inter_y[int(line[0])]+0.5),0.5,0.5,fc='r'))
            else:
                if inter_x[int(line[0])] > inter_x[int(i)]:
                    plt.gca().add_patch(Rectangle((inter_x[int(line[0])]-1,inter_y[int(line[0])]-0.25),0.5,0.5,fc='r'))
                if inter_x[int(line[0])] < inter_x[int(i)]:
                    plt.gca().add_patch(Rectangle((inter_x[int(line[0])]+0.5,inter_y[int(line[0])]-0.25),0.5,0.5,fc='r'))
    f.close()
    
    plt.show() 
Example 43
Project: st_analysis   Author: jfnavarro   File: visualization.py    MIT License 4 votes vote down vote up
def scatter_plot3d(x_points, y_points, z_points, output=None,
                   colors=None, cmap=None, title='Scatter', xlabel=None, 
                   ylabel=None, zlabel=None, alpha=1.0, size=10, vmin=None, vmax=None):
    """ 
    This function makes a scatter 3d plot of a set of points (x,y,z).
    The plot will always use a predefine set of colors unless specified otherwise.
    The plot will be written to a file.
    :param x_points: a list of x coordinates
    :param y_points: a list of y coordinates
    :param z_points: a list of z coordinates (optional)
    :param output: the name/path of the output file
    :param colors: a color label for each point (can be None)
    :param cmap: Matplotlib color mapping object (optional)
    :param title: the title for the plot
    :param xlabel: the name of the X label
    :param ylabel: the name of the Y label
    :param alpha: the alpha transparency level for the dots
    :param size: the size of the dots
    :raises: RuntimeError
    """
    # Plot spots with the color class in the tissue image
    fig = plt.figure()
    a = plt.subplot(projection="3d")
    color_values = None
    unique_colors = set(colors)
    if cmap is None and colors is not None:
        color_values = [color_map[i] for i in unique_colors]
        colors = [color_map[i] for i in colors]
    elif colors is None:
        colors = "blue"
    a.scatter(x_points, 
              y_points,
              z_points,
              c=colors, 
              cmap=cmap, 
              edgecolor="none", 
              s=size,
              alpha=alpha,
              vmin=vmin,
              vmax=vmax)
    a.set_xlabel(xlabel)
    a.set_ylabel(ylabel)
    a.set_zlabel(zlabel)
    if color_values is not None:
        a.legend([plt.Line2D((0,1),(0,0), color=x) for x in color_values], 
                 unique_colors, loc="upper right", markerscale=1.0, 
                 ncol=1, scatterpoints=1, fontsize=5)
    a.set_title(title, size=10)
    # Save or show the plot
    if output is not None:
        fig.savefig("{}.pdf".format(os.path.splitext(os.path.basename(output))[0]), 
                    format='pdf', dpi=300)
        plt.cla()
        plt.close(fig)
    else:
        fig.show() 
Example 44
Project: st_analysis   Author: jfnavarro   File: dimredu_plotter.py    MIT License 4 votes vote down vote up
def plot_tsne(x, y, c, filename, title, xlab, ylab, alpha, size, color_scale, legend, color_bar):
    a = plt.subplot(1, 1, 1)
    # Create the scatter plot
    cmap = cm.get_cmap(color_scale)
    min_v = min(c)
    max_v = max(c)
    sc = a.scatter(x, y, c=c, 
                   edgecolor="none", 
                   cmap=cmap, 
                   s=size,
                   alpha=alpha,
                   vmin=min_v,
                   vmax=max_v)
    # Add legend
    if legend is not None:
        norm = colors.Normalize(vmin=min_v, vmax=max_v)
        unique_c = np.unique(sorted(c))
        a.legend([plt.Line2D((0,1),(0,0), color=cmap(norm(x))) for x in unique_c], 
                 legend, loc="upper right", markerscale=1.0, 
                 ncol=1, scatterpoints=1, fontsize=5)
    # Add x/y labels
    if xlab is not None:
        a.set_xlabel(xlab)
    else:
        a.set_xticklabels([])
        a.axes.get_xaxis().set_visible(False)
    if ylab is not None:
        a.set_ylabel(ylab)
    else:
        a.set_xticklabels([])
        a.axes.get_yaxis().set_visible(False)
    # Add title
    a.set_title(title, size=12)
    # Add color bar
    if color_bar:
        plt.colorbar(sc)
    # Save the plot in a file if the file name is given
    if filename is not None:
        fig = plt.gcf()
        fig.savefig("{}.pdf".format(filename), format='pdf')
        plt.cla()
        plt.close(fig)
    else:
        plt.show() 
Example 45
Project: moose-full   Author: dilawar   File: rc19.py    GNU General Public License v2.0 4 votes vote down vote up
def run_sim_parallel(passive=True, solver='hsolve'):
    data_info_list = []
    model_info_list = []
    for jj, ti in enumerate(intervals):
        for ii, st in enumerate(stim_order):
            experiment_name = 'expt_%d_%d' % (jj, ii)
            dinfo, minfo = setup_experiment(experiment_name, st, tonset, ti, passive=passive, solver=solver)
            data_info_list.append(dinfo)
            model_info_list.append(minfo)
    mutils.setDefaultDt(elecdt=simdt)
    mutils.assignDefaultTicks()
    moose.reinit()
    moose.start(tstop)
    print '$$$$$$$$$$$', moose.element('/clock'    ).currentTime  
    fig = plt.figure()
    axes_vm = fig.add_subplot(111)
    # axes_vm_out = fig.add_subplot(121)
    # axes_vm_in = fig.add_subplot(122, sharex=axes_vm_out, sharey=axes_vm_out)
    ################
    # axes_vm = fig.add_subplot(311)
    # axes_nmda = fig.add_subplot(312)
    # axes_ampa = fig.add_subplot(313)
    for jj, ti in enumerate(intervals):
        for ii, st in enumerate(stim_order):
            dinfo = data_info_list[jj * len(stim_order) + ii]
            print 'Interval=', ti, 'Stim order=', st
            print 'dinfo:', dinfo
            print dinfo['soma_vm']
            print dinfo['soma_vm'].vector
            v = dinfo['soma_vm'].vector
            t = np.linspace(0, tstop, len(v))
            print 'num points=', len(t), 't0=', t[0], 't_last=', t[-1], 'v0=', v[0], 'v_last=', v[-1]
            axes_vm.plot(t, v)
            # if ii % 2 == 0:
            #     axes_vm_in.plot(t,
            #                     v,
            #                     color=color[ii])
            # else:
            #     axes_vm_out.plot(t,
            #                      v,
            #                      color=color[ii])
            # for tab in dinfo['nmda_gk']:
            #     axes_nmda.plot(np.linspace(0, tstop, len(tab.vector)),
            #                    tab.vector, color=color[ii])
            # # axes_nmda.legend()
            # for tab in dinfo['ampa_gk']:
            #     axes_ampa.plot(np.linspace(0, tstop, len(tab.vector)),
            #                    tab.vector, label='%s/%s' % (dinfo['data'].name, tab.name), color=color[ii])
    # axes_vm.legend([plt.Line2D([0], [0], color=color[ii]) for ii in range(len(stim_order))],
    #                [str(st) for st in stim_order])
    #axes_vm.legend()
    #axes_nmda.legend()
    #axes_ampa.legend()
    plt.show() 
Example 46
Project: treeseq-inference   Author: mcveanlab   File: plot.py    Apache License 2.0 4 votes vote down vote up
def plot(self):
        df = self.data
        recombination_linestyles = [':', '-', '--']
        recombination_rates = np.sort(df.recombination_rate.unique())
        mutation_rates = df.mutation_rate.unique()
        tools = df.tool.unique()
        assert len(recombination_linestyles) >= len(recombination_rates)
        assert len(mutation_rates) == len(tools) == 1
        mu = mutation_rates[0]
        tool = tools[0]
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6), sharey=True)
        ax1.set_title("Fixed number of chromosomes ({})".format(self.fixed_sample_size))
        ax1.set_xlabel("Sequence length (MB)")
        ax1.set_ylabel(self.y_axis_label)
        for linestyle, rho in zip(recombination_linestyles, recombination_rates):
            line_data = df.query("(sample_size == @self.fixed_sample_size) and (recombination_rate == @rho)")
            ax1.errorbar(
                line_data.length, line_data[self.plotted_column + "_mean"],
                yerr=None, # line_data[self.plotted_column + "_se"],
                linestyle=linestyle,
                color=self.tools_format[tool]["col"],
                #marker=self.tools_format[tool]['mark'],
                #elinewidth=1
                )


        ax2.set_title("Fixed sequence length ({:g} Mb)".format(self.fixed_length))
        ax2.set_xlabel("Sample size")
        for linestyle, rho in zip(recombination_linestyles, recombination_rates):
            line_data = df.query("(length == @self.fixed_length) and (recombination_rate == @rho)")
            ax2.errorbar(
                line_data.sample_size, line_data[self.plotted_column + "_mean"],
                yerr=None, # line_data[self.plotted_column + "_se"],
                linestyle=linestyle,
                color=self.tools_format[tool]["col"],
                #marker=self.tools_format[tool]['mark'],
                #elinewidth=1
                )
        params = [
            plt.Line2D((0,0),(0,0), color=self.tools_format[tool]["col"],
                linestyle=linestyle, linewidth=2)
            for linestyle, rho in zip(recombination_linestyles, recombination_rates)]
        ax1.legend(
            params,
            [r"$\rho$ = {}".format("$\mu$" if rho==mu else
                r"{:g}$\mu$ (more recombination)".format(rho/mu) if rho>mu else
                r"$\mu$/{:g} (less recombination)".format(mu/rho))
                for rho_index, rho in enumerate(recombination_rates)],
            loc="upper right", fontsize=10, title="Relative rate of recombination")

        self.save() 
Example 47
Project: treeseq-inference   Author: mcveanlab   File: plot.py    Apache License 2.0 4 votes vote down vote up
def plot(self):
        averaging_method = self.data.averaging.unique()
        eff_sizes = self.data.Ne.unique()
        rhos = self.data.recombination_rate.unique()
        lengths = self.data.length.unique()
        assert len(averaging_method) == len(eff_sizes) == len(rhos) == 1
        rho = rhos[0]
        method = averaging_method[0]

        sample_sizes = self.data.sample_size.unique()
        # x-direction is different error rates
        seq_error_params = self.data.error_param.unique()
        # y-direction is the permutations of metric + whether it is rooted
        metric_and_rooting = self.data.groupby(["metric", "rooting"]).groups
        metric_and_rooting = collections.OrderedDict( # make a consistent order
            sorted(metric_and_rooting.items(), key=lambda x: x[0]))
        # sort this so that metrics come out in a set order (TO DO)
        fig, axes = plt.subplots(len(metric_and_rooting), len(seq_error_params),
            squeeze=False, sharey='row',
            figsize=(6*len(seq_error_params), 15))
        for j, ((metric, root), rows) in enumerate(metric_and_rooting.items()):
            for k, error in enumerate(seq_error_params):
                # we are in the j,k th subplot
                ax = axes[j][k]
                ax.set_xscale('log')
                display_order = self.single_metric_plot(
                    self.data.loc[rows].query("error_param == @error"), "mutation_rate",
                    ax, method, rho, markers = (len(sample_sizes)!=1))
                # Use integers for labels
                ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))
                # Make the labels on each Y axis line up properly
                ax.get_yaxis().set_label_coords(-0.08,0.5)
                if j == 0:
                    ax.set_title(self.error_label(error))
                if j == len(metric_and_rooting) - 1:
                    ax.set_xlabel("Mutation rate")
                if k == 0:
                    ax.set_ylim(getattr(self,'ylim', 0))
                    rooting_suffix = " (unrooted)" if root=="unrooted" else ""
                    ylab = getattr(self, 'y_axis_label', self.metric_titles[metric] + rooting_suffix)
                    ax.set_ylabel(ylab)

        artists = [
            plt.Line2D((0,1),(0,0), linewidth=2,
                color=self.tools_format[d.tool]["col"],
                linestyle=self.polytomy_and_averaging_format[d.polytomies][method]["linestyle"],
                marker = None if len(sample_sizes)==1 else self.tools_format[d.tool]['mark'])
            for d in display_order[['tool', 'polytomies']].drop_duplicates().itertuples()]
        tool_labels = [d.tool + ("" if d.polytomies == "retained" else (" (polytomies " + d.polytomies + ")"))
            for d in display_order[['tool', 'polytomies']].drop_duplicates().itertuples()]
        axes[0][0].legend(
            artists, tool_labels, numpoints=1, labelspacing=0.1)

        fig.tight_layout()
        self.save() 
Example 48
Project: treeseq-inference   Author: mcveanlab   File: plot.py    Apache License 2.0 4 votes vote down vote up
def plot(self):
        if getattr(self,"hide_polytomy_breaking", None):
            df = self.data.query("polytomies != 'broken'")
        else:
            df = self.data
        for metric, rooting in self.output_metrics:
            df = df.query("(metric == @metric) and (rooting == @rooting)")
            output_freqs = df[['output_frequency', 'output_after_generations']].drop_duplicates()
            averaging_method = df.averaging.unique()
            eff_sizes = df.Ne.unique()
            rhos = df.recombination_rate.unique()
            lengths = df.length.unique()
            assert len(averaging_method) == len(eff_sizes) == len(rhos) == 1
            rho = rhos[0]
            method = averaging_method[0]
            # x-direction is different error rates
            seq_error_params = df.error_param.unique()
            fig, axes = plt.subplots(len(output_freqs), len(seq_error_params),
                figsize=getattr(self,'figsize',(6*len(seq_error_params), 2.5*len(output_freqs))),
                squeeze=False, sharey=True)
            for j, output_data in enumerate(output_freqs.itertuples()):
                for k, error in enumerate(seq_error_params):
                    ax = axes[j][k]
                    freq = output_data.output_frequency
                    gens = output_data.output_after_generations
                    query = ["error_param == @error"]
                    query.append("output_frequency == @freq")
                    query.append("output_after_generations == @gens")
                    display_order = self.single_metric_plot(
                        df.query("(" + ") and (".join(query) + ")"),
                        "mutation_rate", ax, method, rho)
                    ax.set_xscale('log')
                    if j == 0:
                        ax.set_title(self.error_label(error))
                    if j == len(output_freqs) - 1:
                        ax.set_xlabel("Neutral mutation rate")
                    if k == 0:
                        ax.set_ylabel(getattr(self, 'y_axis_label', metric + " metric") +
                            " @ {}{}".format(
                                "fixation " if np.isclose(freq, 1.0) else "freq {}".format(freq),
                                "+{} gens".format(int(gens)) if gens else ""))
                    if np.isclose(freq, 1.0) and not gens:
                        # This is *at* fixation - set the plot background colour
                        ax.set_facecolor('0.9')
            # Create legends from custom artists
            artists = [
                plt.Line2D((0,1),(0,0),
                    color=self.tools_format[d.tool]["col"],
                    linestyle=self.polytomy_and_averaging_format[d.polytomies][method]["linestyle"],
                    marker = self.tools_format[d.tool]['mark'])
                for d in display_order[['tool', 'polytomies']].drop_duplicates().itertuples()]
            tool_labels = [d.tool + ("" if d.polytomies == "retained" else (" (polytomies " + d.polytomies + ")"))
                for d in display_order[['tool', 'polytomies']].drop_duplicates().itertuples()]
            first_legend = axes[0][0].legend(
                artists, tool_labels, numpoints=1, labelspacing=0.1, loc="upper right")
            fig.tight_layout()
            if len(self.output_metrics)==1:
                self.save()
            else:
                self.save("_".join([self.name, metric, rooting])) 
Example 49
Project: treeseq-inference   Author: mcveanlab   File: plot.py    Apache License 2.0 4 votes vote down vote up
def plot(self):
        self.polytomy_and_averaging_format['retained']['per variant']['linestyle'] = "-"
        for metric, rooting in self.output_metrics:
            query = ["metric == @metric", "rooting == @rooting"]
            if getattr(self,"hide_polytomy_breaking", None):
                query.append("polytomies != 'broken'")
            df = self.data.query("(" + ") and (".join(query) + ")")
            subsample_size = df.subsample_size.unique()
            # all should have the same similarion sample size (but inference occurs on
            # different subsample sizes, and tree comparisons on a fixed small tip #.
            averaging_method = self.data.averaging.unique()
            sample_sizes = df.sample_size.unique()
            all_tree_tips = df.restrict_sample_size_comparison.unique()
            mutation_rates = df.mutation_rate.unique()
            assert len(all_tree_tips) == len(mutation_rates) == len(sample_sizes) == len(averaging_method) == 1
            tree_tips = all_tree_tips[0]
            method = averaging_method[0]
            lengths = df.length.unique()
            seq_error_params = df.error_param.unique()
            fig, axes = plt.subplots(1, len(seq_error_params),
                figsize=(12, 6), squeeze=False, sharey=True)
            for k, error in enumerate(seq_error_params):
                ax = axes[0][k]
                display_order = self.single_metric_plot(
                    df.query("error_param == @error"), "subsample_size",
                    ax, method, rho = None, markers = False, x_jitter = 'log')
                ax.set_title(self.error_label(error))
                if k == 0:
                    ylab = getattr(self, 'y_axis_label', self.metric_titles[metric])
                    ax.set_ylabel("Average " + ylab + " for trees reduced to first {} samples".format(tree_tips))
                ax.set_xlabel("Sample size used for inference")
                ax.set_xscale('log')
            if len(display_order)>1:
                l_order = {v:k for k,v in enumerate(display_order.length.unique())}
                artists = [
                    plt.Line2D((0,1),(0,0),
                        color=self.length_format[d.tool][l_order[d.length]]["col"],
                        linestyle=self.polytomy_and_averaging_format[d.polytomies][method]["linestyle"],
                        marker = False)
                    for d in display_order[['length', 'tool', 'polytomies']].drop_duplicates().itertuples()]
                labels = ["{} kb".format(d.length//1000)
                    for d in display_order[['length']].drop_duplicates().itertuples()]
                first_legend = axes[0][0].legend(
                    artists, labels, numpoints=1, labelspacing=0.1, loc="upper right")
            fig.tight_layout()
            if len(self.output_metrics)==1:
                self.save()
            else:
                self.save("_".join([self.name, metric, rooting])) 
Example 50
Project: xsboringen   Author: tomvansteijn   File: plotting.py    MIT License 4 votes vote down vote up
def get_legend(self, ax):
        handles_labels = []
        if len(self.cs.boreholes) > 0:
            for label, style in self.styles['verticals'].items():
                handles_labels.append((
                    plt.Line2D([0, 1], [0, 1],
                        **style,
                        ),
                    label
                    ))
        for label, style in self.styles['surfaces'].items():
            handles_labels.append((
                plt.Line2D([0, 1], [0, 1],
                    **style,
                    ),
                label
                ))
        if len(self.cs.boreholes) > 0:
            for label, style in self.styles['segments'].items():
                handles_labels.append((
                    plt.Rectangle((0, 0), 1, 1,
                        **style,
                        ),
                    label
                    ))
        for label, style in self.styles['solids'].items():
            handles_labels.append((
                plt.Rectangle((0, 0), 1, 1,
                    **style,
                    ),
                label
                ))
        handles, labels = zip(*handles_labels)

        legend_title = self.cfg.get('legend_title')
        legend_fontsize = self.cfg.get('legend_fontsize')
        lgd = ax.legend(handles, labels,
            title=legend_title,
            fontsize=legend_fontsize,
            loc='lower left',
            bbox_to_anchor=(1.01, 0),
            ncol=self.legend_ncol,
            )
        return lgd