Python matplotlib.patches.Circle() Examples

The following are code examples for showing how to use matplotlib.patches.Circle(). 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: Graphvy   Author: anbarief   File: graphvy.py    MIT License 6 votes vote down vote up
def gen_plot(self, obj):

        if len(self.graph.nodes) > 0:

            self.fig, self.ax = plt.subplots()
            self.ax.set_axis_bgcolor(Window.clearcolor)
            self.ax.axis('square')
            for e in self.graph.edges:
                points = e.line_coordinates
                self.ax.plot([points[0], points[2]], [points[1], points[3]], '-', color = e.color)

            for i in self.graph.nodes:
                x, y = i.coordinates[0], i.coordinates[1]
                circle = Circle(xy = [x, y], radius = 12.5, fc = i.visual_color, ec = "black")
                self.ax.add_patch(circle)
                self.ax.text(x, y, i.visual_text, fontsize = 8)

        
            self.ax.set_xlim([self.graph.nodes_xmin, self.graph.nodes_xmax])
            self.ax.set_ylim([self.graph.nodes_ymin, self.graph.nodes_ymax])
            plt.show(self.fig) 
Example 2
Project: ddpg-curiosity-and-multi-criteria-her   Author: CDMCH   File: heatmap_gen.py    MIT License 6 votes vote down vote up
def plot_3D_cylinder(ax, radius, height, elevation=0, resolution=100, color='gray', x_center=0., y_center=0.):
    x = np.linspace(x_center-radius, x_center+radius, resolution)
    z = np.linspace(elevation, elevation+height, resolution)
    X, Z = np.meshgrid(x, z)

    Y = np.sqrt(radius**2 - (X - x_center)**2) + y_center # Pythagorean theorem

    ax.plot_surface(X, Y, Z, linewidth=0, color=color)
    ax.plot_surface(X, (2*y_center-Y), Z, linewidth=0, color=color)

    floor = Circle((x_center, y_center), radius, color=color)
    ax.add_patch(floor)
    art3d.pathpatch_2d_to_3d(floor, z=elevation, zdir="z")

    ceiling = Circle((x_center, y_center), radius, color=color)
    ax.add_patch(ceiling)
    art3d.pathpatch_2d_to_3d(ceiling, z=elevation+height, zdir="z") 
Example 3
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 6 votes vote down vote up
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
    # https://matplotlib.org/examples/color/colormaps_reference.html
    patches = []
    for pos in var:
        if shape == 'c':
            patches.append(mpatches.Circle(pos, r))
        elif shape == 'r':
            patches.append(mpatches.RegularPolygon(pos, 4, r))
        elif shape == 's':
            patches.append(mpatches.RegularPolygon(pos, 6, r))

    colors = np.linspace(start_color, .9, len(patches))
    collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
    collection.set_array(np.array(colors))
    collection.set_clim(0, 1)
    return collection 
Example 4
Project: statistical_mechanics_teaching   Author: mabau   File: mpl_display.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, axes, sim, type_to_radius, type_to_color):
        assert len(type_to_radius) == len(type_to_color)

        particle_types_arr = sim.types
        self._typeToRadius = type_to_radius
        self._typeToColor = type_to_color
        self._particleCircles = []
        self._sim = sim
        for particleType in particle_types_arr:
            c = Circle((0, 0, 0), type_to_radius[particleType], )
            c.set_color(self._typeToColor[particleType])
            self._particleCircles.append(c)
            axes.add_patch(c)

        axes.set_xlim([0, sim.domain_size[0]])
        axes.set_ylim([0, sim.domain_size[1]])
        axes.set_aspect('equal') 
Example 5
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axisbelow():
    # Test 'line' setting added in 6287.
    # Show only grids, not frame or ticks, to make this test
    # independent of future change to drawing order of those elements.
    fig, axs = plt.subplots(ncols=3, sharex=True, sharey=True)
    settings = (False, 'line', True)

    for ax, setting in zip(axs, settings):
        ax.plot((0, 10), (0, 10), lw=10, color='m')
        circ = mpatches.Circle((3, 3), color='r')
        ax.add_patch(circ)
        ax.grid(color='c', linestyle='-', linewidth=3)
        ax.tick_params(top=False, bottom=False,
                       left=False, right=False)
        for spine in ax.spines.values():
            spine.set_visible(False)
        ax.set_axisbelow(setting) 
Example 6
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_axisbelow():
    # Test 'line' setting added in 6287.
    # Show only grids, not frame or ticks, to make this test
    # independent of future change to drawing order of those elements.
    fig, axs = plt.subplots(ncols=3, sharex=True, sharey=True)
    settings = (False, 'line', True)

    for ax, setting in zip(axs, settings):
        ax.plot((0, 10), (0, 10), lw=10, color='m')
        circ = mpatches.Circle((3, 3), color='r')
        ax.add_patch(circ)
        ax.grid(color='c', linestyle='-', linewidth=3)
        ax.tick_params(top=False, bottom=False,
                       left=False, right=False)
        for spine in ax.spines.values():
            spine.set_visible(False)
        ax.set_axisbelow(setting) 
Example 7
Project: beamprofiler   Author: Spiruel   File: analysis.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_gaussian(self, ax, params):           
        if self.master.colourmap is None:
            cmap=plt.cm.BrBG
        elif self.master.colourmap == 2:
            cmap=plt.cm.jet
        elif self.master.colourmap == 0:
            cmap=plt.cm.autumn
        elif self.master.colourmap == 1:
            cmap=plt.cm.bone
        
        ax.imshow(self.crop_img, cmap=cmap, interpolation='nearest', origin='lower')

        # ax.scatter(params[0], params[1], s=100, c="red", marker="x")

        circle = Circle((params[0], params[1]), params[2], facecolor='none',
                edgecolor="red", linewidth=1, alpha=0.8)
        ax.add_patch(circle) 
Example 8
Project: tools   Author: sgs-us   File: lbPlot.py    GNU General Public License v3.0 6 votes vote down vote up
def lb2D():
    # define some colors
    colors = iter(cm.rainbow(np.linspace(0, 1, 9)))
    for offset in list(product([-1, 0, 1], repeat=2)):
        origin = [0.5, 0.5]
        rect = Rectangle ((0 + offset[0], 0 + offset[1]), # xy
                          1,                              # width
                          1,                              # height
                          ec = "black",                   # edge color
                          fc = [0, 0, 0, 0],              # face color = transparent
                          zorder=1)                       # specify stacking
        ax2.add_patch(rect)
        if offset[0] != 0 or offset[1] != 0:
            arrow = Arrow(origin[0], origin[1], offset[0], offset[1], width = 0.5, color=next(colors),zorder=0)
            ax2.add_patch(arrow)
    # draw c_0
    circ = Circle((origin[0], origin[1]), 0.125, color="black", zorder=2)
    ax2.add_patch(circ)
    fig2.savefig("d2q9.png") 
Example 9
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axisbelow():
    # Test 'line' setting added in 6287.
    # Show only grids, not frame or ticks, to make this test
    # independent of future change to drawing order of those elements.
    fig, axs = plt.subplots(ncols=3, sharex=True, sharey=True)
    settings = (False, 'line', True)

    for ax, setting in zip(axs, settings):
        ax.plot((0, 10), (0, 10), lw=10, color='m')
        circ = mpatches.Circle((3, 3), color='r')
        ax.add_patch(circ)
        ax.grid(color='c', linestyle='-', linewidth=3)
        ax.tick_params(top=False, bottom=False,
                       left=False, right=False)
        for spine in ax.spines.values():
            spine.set_visible(False)
        ax.set_axisbelow(setting) 
Example 10
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 5 votes vote down vote up
def plot_3d_ball_trajectory(var, filename, r=0.05):
    var = np.asarray(var)

    # Normalize directions
    var -= var.min(axis=0)
    var /= var.max(axis=0)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    for x, y, z in var:
        p = mpatches.Circle((x, y), r, ec="none")
        ax.add_patch(p)
        art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

        p = mpatches.Circle((x, z), r, ec="none")
        ax.add_patch(p)
        art3d.pathpatch_2d_to_3d(p, z=0, zdir="y")

        p = mpatches.Circle((y, z), r, ec="none")
        ax.add_patch(p)
        art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")

        # ax.scatter(x, y, z, s=100)
    # ax.plot(var[:, 0], var[:, 1], zs=var[:, 2])

    ax.view_init(azim=45, elev=30)
    ax.set_xlim3d(-0.1, 1.1)
    ax.set_ylim3d(-0.1, 1.1)
    ax.set_zlim3d(-0.1, 1.1)
    plt.savefig(filename, format='png', bbox_inches='tight', dpi=80)
    plt.close(fig)
    # plt.show() 
Example 11
Project: pyplis   Author: jgliss   File: ex07_doas_cell_calib.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_doas_fov(fov_x, fov_y, fov_extend, ax):
    # add FOV position to plot of examplary AA image
    c = Circle((fov_x, fov_y), fov_extend, ec="k", fc="lime", alpha=.5)
    ax.add_artist(c)
    ax.text(fov_x, (fov_y - fov_extend * 1.3), "DOAS FOV")
    ax.set_xlim([0, 1343]), ax.set_ylim([1023, 0])
    return ax 
Example 12
Project: LaserTOF   Author: kyleuckert   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 13
Project: LaserTOF   Author: kyleuckert   File: polar.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 14
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 15
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 16
Project: numerical_analysis   Author: lcharleux   File: core.py    GNU General Public License v2.0 5 votes vote down vote up
def draw(self, ax, deformed = True, radius = 0.03, label = True, force_factor = 5.):
    """
    Draws the node.
    """
    pos = self.coords.copy()
    if deformed: pos += self.displacement
    patch = patches.Circle(pos, radius, color='k',clip_on=False)
    ax.add_artist(patch)
    if label == True:
      if self.label != None:
        an = ax.annotate(self.label, xy=pos,  xycoords='data',
                    xytext=(-50, 30), textcoords='offset points',
                    bbox=dict(boxstyle="round", fc="1.",clip_on=False),
                    arrowprops=dict(arrowstyle="<-",
                                    connectionstyle="angle,angleA=0,angleB=90,rad=10")
                    )
        an.draggable()
    if self.block[0]:
      d = radius * 2.
      bs = self.block_side
      verts = np.array([[-.1,0.], [-1.,.9], [-1.,-.9], [-.1, 0.]]) 
      verts *= d
      verts += pos
      p = patches.Polygon(verts, facecolor = "none",clip_on=False, linewidth = 1.5)
      ax.add_artist(p)
      p = patches.Circle(pos + np.array([-1.5, .5])*d, d*.5, facecolor='none',clip_on=False, linewidth = 1.5)  
      ax.add_artist(p) 
      p = patches.Circle(pos + np.array([-1.5, -.5])*d, d*.5, facecolor='none',clip_on=False, linewidth = 1.5)  
      ax.add_artist(p) 
    if self.block[1]:
      d = radius * 2.
      
      verts = np.array([[0.,-.1], [-.9, -1.], [.9,-1.], [0., -.1]]) 
      verts *= d
      verts += pos
      p = patches.Polygon(verts, facecolor = "none",clip_on=False, linewidth = 1.5)
      ax.add_artist(p)
      p = patches.Circle(pos + np.array([-.5, -1.5])*d, d*.5, facecolor='none',clip_on=False, linewidth = 1.5)  
      ax.add_artist(p) 
      p = patches.Circle(pos + np.array([.5, -1.5])*d, d*.5, facecolor='none',clip_on=False, linewidth = 1.5)  
      ax.add_artist(p) 
Example 17
Project: ble5-nrf52-mac   Author: tomasero   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 18
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_mixed_collection():
    from matplotlib import patches
    from matplotlib import collections

    x = list(range(10))

    # First illustrate basic pyplot interface, using defaults where possible.
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')

    # PDF can optimize this one
    p1 = collections.PatchCollection([c], match_original=True)
    p1.set_offsets([[0, 0], [24, 24]])
    p1.set_linewidths([1, 5])

    # PDF can't optimize this one, because the alpha of the edge changes
    p2 = collections.PatchCollection([c], match_original=True)
    p2.set_offsets([[48, 0], [-32, -16]])
    p2.set_linewidths([1, 5])
    p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])

    ax.patch.set_color('0.5')
    ax.add_collection(p1)
    ax.add_collection(p2)

    ax.set_xlim(0, 16)
    ax.set_ylim(0, 16) 
Example 19
Project: ble5-nrf52-mac   Author: tomasero   File: test_image.py    MIT License 5 votes vote down vote up
def test_image_clip():
    d = [[1, 2], [3, 4]]

    fig, ax = plt.subplots()
    im = ax.imshow(d)
    patch = patches.Circle((0, 0), radius=1, transform=ax.transData)
    im.set_clip_path(patch) 
Example 20
Project: nanopores   Author: mitschabaude   File: randomwalk.py    MIT License 5 votes vote down vote up
def polygon_patches(self, cyl=False):
        poly_settings = dict(closed=True, facecolor="#eeeeee", linewidth=1.,
                        edgecolor="k")
        ball_settings = dict(facecolor="#aaaaaa", linewidth=1., edgecolor="k",
                             alpha=0.5)
        ball_bind_zone_settings = dict(facecolor="#ffaaaa", linewidth=0.,
                                       alpha=0.5)
        patches = []
        for dom in self.domains:
            domp = dom.domain
            if isinstance(domp, Polygon):
                polygon = domp.nodes
                polygon = np.array(polygon)
                patches.append(mpatches.Polygon(polygon, **poly_settings))
                if not cyl:
                    polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
                    patches.append(mpatches.Polygon(polygon_m, **poly_settings))
            elif isinstance(domp, Ball):
                xy = domp.x0[0], domp.x0[2]
                if dom.binding and dom.bind_type == "zone":
                    p1 = mpatches.Circle(xy, domp.r + dom.ra,
                                         **ball_bind_zone_settings)
                    p1.set_zorder(-100)
                    patches.append(p1)
                
                p = mpatches.Circle(xy, domp.r, **ball_settings)
                p.set_zorder(200)
                patches.append(p)
        return patches 
Example 21
Project: nanopores   Author: mitschabaude   File: plot_2D_pore_geometries.py    MIT License 5 votes vote down vote up
def add_ball(ax, x, y, r, **settings):
    p = mpatches.Circle((x, y), r, **dict(ball_settings, **settings))
    p.set_zorder(200)
    ax.add_patch(p)

############################################################### 
Example 22
Project: nanopores   Author: mitschabaude   File: plot_robustness.py    MIT License 5 votes vote down vote up
def plot_circle(ax, x, y, color):
    area = 380    
    circle = ax.scatter(x, y, s=area, c=color)
    #edgewidth = 0
    #edgecolor = "k" # black      
    #circle = ax.plot(x, y, "o", c=color, markersize=10)
    #circle= mpatches.Circle((x, y), radius, fc=color, ec=edgecolor, lw=edgewidth)
    #ax.add_patch(circle)
    return circle 
Example 23
Project: nanopores   Author: mitschabaude   File: plot_robustness.py    MIT License 5 votes vote down vote up
def plot_robustness(ax, fpdata, fplabels, fpcolors):    
    handles = OrderedDict() # for legend
    
    for data, label, color in zip(fpdata, fplabels, fpcolors):
        handle = []
        
        # nice painless way to iterate array:
        array = np.nditer(data, flags=['multi_index'])    
        for boolean in array:
            if boolean:
                i, j = array.multi_index
                x, y = X[i], Y[j]
                circle = plot_circle(ax, x, y, color)
                handle.append(circle)
                
        handles[label] = tuple(handle)
    
    # TODO: axis limits
    #ax.set_aspect('equal', 'datalim')
    #ax.autoscale_view(True,True,True)
    ax.set_xscale("log")#, subsx=[2,5])
    ax.set_yscale("log")#, subsy=[2,5])
    
    myhandles = [plt.Rectangle((0, 0), 1, 1, fc=col) for col in fpcolors]
    #ax.legend([h[0] for h in handles.values()], handles.keys(),
    ax.legend(myhandles, handles.keys(),
        #bbox_to_anchor=(0.5, 1.05), loc="lower center", borderaxespad=0.,)
        bbox_to_anchor=(0., 1.5), loc="upper left", borderaxespad=0.,)
        #handler_map={mpatches.Circle:HandlerPatch(patch_func=make_legend_ellipse)})
    ax.set_xlabel("voltage bias [V]")
    ax.set_ylabel(r"surface charge density [q/nm$^2$]")
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

# --- fixed point --- 
Example 24
Project: Computable   Author: ktraunmueller   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 25
Project: Computable   Author: ktraunmueller   File: polar.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 26
Project: Computable   Author: ktraunmueller   File: proj3d.py    MIT License 5 votes vote down vote up
def test_lines_dists():
    import pylab
    ax = pylab.gca()

    xs, ys = (0,30), (20,150)
    pylab.plot(xs, ys)
    points = zip(xs, ys)
    p0, p1 = points

    xs, ys = (0,0,20,30), (100,150,30,200)
    pylab.scatter(xs, ys)

    dist = line2d_seg_dist(p0, p1, (xs[0], ys[0]))
    dist = line2d_seg_dist(p0, p1, np.array((xs, ys)))
    for x, y, d in zip(xs, ys, dist):
        c = Circle((x, y), d, fill=0)
        ax.add_patch(c)

    pylab.xlim(-200, 200)
    pylab.ylim(-200, 200)
    pylab.show() 
Example 27
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: ebo.py    MIT License 5 votes vote down vote up
def plot_ebo(tree, newX, t):
    # visualize EBO on 2D function
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    ax, fig = tree.visualize()
    for x in newX:
        c = '#1f78b4'
        p = patches.Circle(
            x, 0.01,
            facecolor=c,
            linewidth=0
        )
        ax.add_patch(p)
    plt.show()
    fig.savefig('ebo_result_iteration_' + str(t) + '.eps', format='eps', dpi=1000) 
Example 28
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: mondrian.py    MIT License 5 votes vote down vote up
def visualize(self):
        if self.leaves is None or self.X.shape[1] != 2:
            print
            'error: x shape is wrong or leaves is none.'

        # visaulize 2d mondrians
        import matplotlib.pyplot as plt
        import matplotlib.patches as patches
        import matplotlib
        font = {'size': 20}
        matplotlib.rc('font', **font)
        mondrian_colors = np.array([[255, 240, 1], [48, 48, 58],
                                    [255, 1, 1], [1, 1, 253], [249, 249, 249]])
        mondrian_colors = mondrian_colors / 255.0
        fig = plt.figure()
        ax = fig.add_subplot(111, aspect='equal')
        print('number of leaves = {}'.format(len(self.leaves)))
        for node in self.leaves:
            xy = node.x_range[0]
            xylen = node.x_range[1] - node.x_range[0]
            c = mondrian_colors[4]
            p = patches.Rectangle(
                xy, xylen[0], xylen[1],
                facecolor=c,
                linewidth=1,
                edgecolor='k'
            )
            ax.add_patch(p)
        for x in self.X:
            c = '#fdbf6f'
            p = patches.Circle(
                x, 0.01,
                facecolor=c,
                linewidth=0
            )
            ax.add_patch(p)
        return ax, fig 
Example 29
Project: viznet   Author: GiggleLiu   File: shapes.py    MIT License 5 votes vote down vote up
def empty(xy, *args, **kwargs):
    c = patches.Circle(xy, 0, edgecolor='none', facecolor='none')
    return [c] 
Example 30
Project: viznet   Author: GiggleLiu   File: shapes.py    MIT License 5 votes vote down vote up
def circle(xy, size, angle=None, roundness=0, props={}, **kwargs):
    c = patches.Circle(xy, size, **_fix(kwargs))
    return [c] 
Example 31
Project: prob_meteogram   Author: milankl   File: meteogram_alderaan.py    MIT License 5 votes vote down vote up
def clouds_plotter(axis,dates,highcloud,midcloud,lowcloud, interp=True):
    """ Adds the different types of clouds to a given axis."""
    # add sun (and moon?)
    for t in np.arange(len(dates)):
        idate = datetime.datetime(2018,6,7,12,0)
        while idate < dates[-1]:
            #sun = Circle((dates[t], 0.5), 0.2, color='yellow', zorder=0)
            sun = Ellipse((idate, 0.5), 0.4/2., 0.5, angle=0.0, color='yellow', zorder=0)
            axis.add_artist(sun)
            idate = idate + datetime.timedelta(1)

    # interpolate dates (if set)
    if interp:
        dates = spline_dates(dates)

    # add mean cloud covers and scale to [0...1]
    highcloudm = np.median(highcloud,axis=1)
    midcloudm = np.median(midcloud,axis=1)
    lowcloudm = np.median(lowcloud,axis=1)

    totalcloud=(highcloudm+midcloudm+lowcloudm)/3.
    totalcloudhalf=totalcloud/2.
    lowerbound=-totalcloudhalf+0.5
    upperbound=totalcloudhalf+0.5

    # don't plot clouds where totalcloud <= e.g. 0.05
    threshold=0.05

    # highcloud light grey, lowcloud dark grey
    axis.fill_between(dates, y1=lowerbound, y2=upperbound, color='0.95',zorder=1, alpha=0.8, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=upperbound-highcloudm/3., color='0.7',zorder=2, alpha=0.6, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=lowerbound+lowcloudm/3.,  color='0.4',zorder=3, alpha=0.3, edgecolor='none',where=totalcloud>=threshold)
    axis.set_facecolor('lightskyblue') 
Example 32
Project: prob_meteogram   Author: milankl   File: meteogram.py    MIT License 5 votes vote down vote up
def clouds_plotter(axis,dates,highcloud,midcloud,lowcloud, interp=True):
    """ Adds the different types of clouds to a given axis."""
    # add sun (and moon?)
    for t in np.arange(len(dates)):
        idate = datetime.datetime(2018,6,7,12,0)
        while idate < dates[-1]:
            #sun = Circle((dates[t], 0.5), 0.2, color='yellow', zorder=0)
            sun = Ellipse((idate, 0.5), 0.4/2., 0.5, angle=0.0, color='yellow', zorder=0)
            axis.add_artist(sun)
            idate = idate + datetime.timedelta(1)

    # interpolate dates (if set)
    if interp:
        dates = spline_dates(dates)

    # add mean cloud covers and scale to [0...1]
    highcloudm = np.median(highcloud,axis=1)
    midcloudm = np.median(midcloud,axis=1)
    lowcloudm = np.median(lowcloud,axis=1)

    totalcloud=(highcloudm+midcloudm+lowcloudm)/3.
    totalcloudhalf=totalcloud/2.
    lowerbound=-totalcloudhalf+0.5
    upperbound=totalcloudhalf+0.5

    # don't plot clouds where totalcloud <= e.g. 0.05
    threshold=0.05

    # highcloud light grey, lowcloud dark grey
    axis.fill_between(dates, y1=lowerbound, y2=upperbound, color='0.95',zorder=1, alpha=0.8, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=upperbound-highcloudm/3., color='0.7',zorder=2, alpha=0.6, edgecolor='none',where=totalcloud>=threshold)
    axis.fill_between(dates, y1=lowerbound, y2=lowerbound+lowcloudm/3.,  color='0.4',zorder=3, alpha=0.3, edgecolor='none',where=totalcloud>=threshold)
    axis.set_facecolor('lightskyblue') 
Example 33
Project: pylustrator   Author: rgerum   File: parse_svg.py    GNU General Public License v3.0 5 votes vote down vote up
def clone_patch(patch):
    if isinstance(patch, mpatches.Rectangle):
        return mpatches.Rectangle(xy=patch.get_xy(),
                                  width=patch.get_width(),
                                  height=patch.get_height())
    if isinstance(patch, mpatches.Circle):
        return mpatches.Circle(xy=patch.get_xy(),
                               radius=patch.get_radius())
    if isinstance(patch, mpatches.Ellipse):
        return mpatches.Ellipse(xy=patch.get_xy(),
                                width=patch.get_width(),
                                height=patch.get_height())
    if isinstance(patch, mpatches.PathPatch):
        return mpatches.PathPatch(patch.get_path()) 
Example 34
Project: pylustrator   Author: rgerum   File: parse_svg.py    GNU General Public License v3.0 5 votes vote down vote up
def patch_circle(node, trans, style, ids):
    if node.getAttribute("d") != "":
        return patch_path(node, trans, style, ids)
    return mpatches.Circle(xy=(float(node.getAttribute("cx")), float(node.getAttribute("cy"))),
                           radius=float(node.getAttribute("r")),
                           transform=trans) 
Example 35
Project: neural-network-animation   Author: miloharper   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 36
Project: neural-network-animation   Author: miloharper   File: polar.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 37
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 5 votes vote down vote up
def test_mixed_collection():
    from matplotlib import patches
    from matplotlib import collections

    x = list(xrange(10))

    # First illustrate basic pyplot interface, using defaults where possible.
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')

    # PDF can optimize this one
    p1 = collections.PatchCollection([c], match_original=True)
    p1.set_offsets([[0, 0], [24, 24]])
    p1.set_linewidths([1, 5])

    # PDF can't optimize this one, because the alpha of the edge changes
    p2 = collections.PatchCollection([c], match_original=True)
    p2.set_offsets([[48, 0], [-32, -16]])
    p2.set_linewidths([1, 5])
    p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])

    ax.patch.set_color('0.5')
    ax.add_collection(p1)
    ax.add_collection(p2)

    ax.set_xlim(0, 16)
    ax.set_ylim(0, 16) 
Example 38
Project: RNAFoldingDeepRL   Author: NetoPedro   File: arc_diagram.py    MIT License 5 votes vote down vote up
def _circle(i, r=.05):
	"""
	Create a small filled circle with center at (i, 0) and radius r
	"""
	return Circle((i,0.4 ), r, fill=True, color='black') 
Example 39
Project: nnv   Author: renatosc   File: nnv.py    MIT License 5 votes vote down vote up
def render(self, m_ax):
        circle = Circle((self.get_center_x(), self.get_center_y()), self.get_radius(), color=self.color)
        m_ax.add_patch(circle)
        return circle 
Example 40
Project: nnv   Author: renatosc   File: nnv.py    MIT License 5 votes vote down vote up
def render(self, m_ax):
        circle = Circle((self.get_center_x(), self.get_center_y()), self.get_radius(), color=self.color)
        m_ax.add_patch(circle)
        return circle 
Example 41
Project: Kobe-Analysis   Author: codeabhious   File: kobeanalysis.py    Apache License 2.0 5 votes vote down vote up
def kobe_shooting_plot(kobe_df,kobeyear,gridNum,isClutch):
    

    #compute shooting percentage and # of shots
    (ShootingPctLocs, shotNumber,shootingFreqLocs) = find_shootingPcts(kobe_df,kobeyear, gridNum,isClutch)
    #draw figure and court
    fig = plt.figure()#(12,7)
    ax = plt.axes([0.1, 0.1, 0.8, 0.8]) #where to place the plot within the figure
    draw_court(outer_lines=False)
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.tick_params(labelbottom='off', labelleft='off')
    plt.xlim(-250,250)
    plt.ylim(400, -25)
    #cdict = {'red': (
    #}
    cmap = plt.cm.RdYlBu
    #mymap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
    #cmap = mymap
    #draw circles
    for i, shots in enumerate(ShootingPctLocs):
        restricted = Circle(shotNumber.get_offsets()[i], radius=shootingFreqLocs[i]*50,
                            color=cmap(shots),alpha=0.8, fill=True)
        
        if restricted.radius > 240/gridNum: restricted.radius=240/gridNum
        ax.add_patch(restricted)

    #draw color bar
    ax2 = fig.add_axes([0.92, 0.1, 0.02, 0.8])
    cb = mpl.colorbar.ColorbarBase(ax2,cmap=cmap, orientation='vertical')
    cb.set_label('Efficiency Compared to Career Avg.')
    cb.set_ticks([0.0,1.0])
    cb.set_ticklabels(['Low %', 'High %'])
    if isClutch:
        plt.suptitle('Kobe Bryant: ' + str(kobeyear) + ' Clutch Shot Chart')
    else:
        plt.suptitle('Kobe Bryant: ' + str(kobeyear) + ' Shot Chart')
    plt.show()
    return ax
    
#kobe_shooting_plot(x,[2006,2007],30,False) 
Example 42
Project: pysisyphus   Author: eljost   File: test_dynamics.py    GNU General Public License v3.0 5 votes vote down vote up
def test_mdp():
    coords = (-0.82200156,  0.6243128, 0)
    geom = MullerBrownPot.get_geom(coords)

    A = (-0.5592, 1.443, 0)
    B = (0.605, 0.036, 0)
    rad = 0.05
    def stopA(x, rad=rad):
        return np.linalg.norm(x-A) < rad
    def stopB(x, rad=rad):
        return np.linalg.norm(x-B) < rad
    term_funcs = (stopA, stopB)

    mdp_kwargs = {
        "E_excess": 0.1,
        "term_funcs": term_funcs,
        "epsilon": 5e-4,
        "ascent_alpha": 0.05,
        "t_init": 0.15,
        "t": 3,
        "dt": 0.001,
    }
    # np.random.seed(25032018)
    res = mdp(geom, **mdp_kwargs)

    calc = geom.calculator
    calc.plot()
    ax = calc.ax
    ax.plot(*res.ascent_xs.T[:2], "ro-")
    ax.plot(*res.md_init_plus.coords.T[:2], "-", lw=3)
    ax.plot(*res.md_init_minus.coords.T[:2], "-", lw=3)
    cA = Circle(A[:2], radius=rad)
    ax.add_artist(cA)
    cB = Circle(B[:2], radius=rad)
    ax.add_artist(cB)
    ax.plot(*res.md_fin_plus.coords.T[:2], "-", lw=3)
    ax.plot(*res.md_fin_minus.coords.T[:2], "-", lw=3)

    plt.show() 
Example 43
Project: GraphicDesignPatternByPython   Author: Relph1119   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 44
Project: python3_ios   Author: holzschu   File: whats_new_98_4_fancy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_arrowstyles(ax):
    styles = mpatch.ArrowStyle.get_styles()

    ax.set_xlim(0, 4)
    ax.set_ylim(0, figheight)

    for i, (stylename, styleclass) in enumerate(sorted(styles.items())):
        y = (float(len(styles)) -0.25 - i) # /figheight
        p = mpatch.Circle((3.2, y), 0.2, fc="w")
        ax.add_patch(p)

        ax.annotate(stylename, (3.2, y),
                    (2., y),
                    #xycoords="figure fraction", textcoords="figure fraction",
                    ha="right", va="center",
                    size=fontsize,
                    arrowprops=dict(arrowstyle=stylename,
                                    patchB=p,
                                    shrinkA=5,
                                    shrinkB=5,
                                    fc="w", ec="k",
                                    connectionstyle="arc3,rad=-0.05",
                                    ),
                    bbox=dict(boxstyle="square", fc="w"))

    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False) 
Example 45
Project: python3_ios   Author: holzschu   File: anatomy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def circle(x, y, radius=0.15):
    from matplotlib.patches import Circle
    from matplotlib.patheffects import withStroke
    circle = Circle((x, y), radius, clip_on=False, zorder=10, linewidth=1,
                    edgecolor='black', facecolor=(0, 0, 0, .0125),
                    path_effects=[withStroke(linewidth=5, foreground='w')])
    ax.add_artist(circle) 
Example 46
Project: python3_ios   Author: holzschu   File: custom_projection.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _gen_axes_patch(self):
        """
        Override this method to define the shape that is used for the
        background of the plot.  It should be a subclass of Patch.

        In this case, it is a Circle (that may be warped by the axes
        transform into an ellipse).  Any data and gridlines will be
        clipped to this shape.
        """
        return Circle((0.5, 0.5), 0.5) 
Example 47
Project: python3_ios   Author: holzschu   File: anchored_artists.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(ax):
    """
    Draw a circle in axis coordinates
    """
    from matplotlib.patches import Circle
    ada = AnchoredDrawingArea(20, 20, 0, 0,
                              loc='upper right', pad=0., frameon=False)
    p = Circle((10, 10), 10)
    ada.da.add_artist(p)
    ax.add_artist(ada) 
Example 48
Project: python3_ios   Author: holzschu   File: simple_anchored_artists.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(ax):
    """
    Draw a circle in axis coordinates
    """
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
    from matplotlib.patches import Circle
    ada = AnchoredDrawingArea(20, 20, 0, 0,
                              loc='upper right', pad=0., frameon=False)
    p = Circle((10, 10), 10)
    ada.da.add_artist(p)
    ax.add_artist(ada) 
Example 49
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_mixed_collection():
    from matplotlib import patches
    from matplotlib import collections

    x = list(range(10))

    # First illustrate basic pyplot interface, using defaults where possible.
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')

    # PDF can optimize this one
    p1 = collections.PatchCollection([c], match_original=True)
    p1.set_offsets([[0, 0], [24, 24]])
    p1.set_linewidths([1, 5])

    # PDF can't optimize this one, because the alpha of the edge changes
    p2 = collections.PatchCollection([c], match_original=True)
    p2.set_offsets([[48, 0], [-32, -16]])
    p2.set_linewidths([1, 5])
    p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])

    ax.patch.set_color('0.5')
    ax.add_collection(p1)
    ax.add_collection(p2)

    ax.set_xlim(0, 16)
    ax.set_ylim(0, 16) 
Example 50
Project: python3_ios   Author: holzschu   File: test_image.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_image_clip():
    d = [[1, 2], [3, 4]]

    fig, ax = plt.subplots()
    im = ax.imshow(d)
    patch = patches.Circle((0, 0), radius=1, transform=ax.transData)
    im.set_clip_path(patch) 
Example 51
Project: SUMO_dy_public   Author: DayuanTan   File: results_mpl.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_net(ax, net, edgecolor="gray", edgewidth=2, color_node=None,
             alpha=0.5):
    for shape in net.edges.shapes.get_value():
        x_vec = np.array(shape)[:, 0]
        y_vec = np.array(shape)[:, 1]
        ax.plot(x_vec, y_vec, color=edgecolor, lw=edgewidth, alpha=alpha)

    # do nodes
    if color_node is None:
        is_nodefill = False
        color_node = 'none'
    else:
        is_nodefill = True

    #ax.scatter(x_vec[0], y_vec[0], s=np.pi * (10.0)**2, c=colors, alpha=0.5)
    coords = net.nodes.coords.get_value()
    radii = net.nodes.radii.get_value()
    #ax.scatter(coords[:,0], coords[:,1], s=np.pi * (radii)**2, alpha=0.5)
    #patches = []
    for coord, radius in zip(coords, radii):
        ax.add_patch(Circle(coord, radius=radius,
                            linewidth=edgewidth,
                            edgecolor=edgecolor,
                            facecolor=color_node,
                            fill=is_nodefill,
                            alpha=alpha)) 
Example 52
Project: linear_neuron   Author: uglyboxer   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 53
Project: linear_neuron   Author: uglyboxer   File: polar.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 54
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 5 votes vote down vote up
def test_mixed_collection():
    from matplotlib import patches
    from matplotlib import collections

    x = list(xrange(10))

    # First illustrate basic pyplot interface, using defaults where possible.
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')

    # PDF can optimize this one
    p1 = collections.PatchCollection([c], match_original=True)
    p1.set_offsets([[0, 0], [24, 24]])
    p1.set_linewidths([1, 5])

    # PDF can't optimize this one, because the alpha of the edge changes
    p2 = collections.PatchCollection([c], match_original=True)
    p2.set_offsets([[48, 0], [-32, -16]])
    p2.set_linewidths([1, 5])
    p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])

    ax.patch.set_color('0.5')
    ax.add_collection(p1)
    ax.add_collection(p2)

    ax.set_xlim(0, 16)
    ax.set_ylim(0, 16) 
Example 55
Project: psychrometric-chart-makeover   Author: buds-lab   File: geo.py    MIT License 5 votes vote down vote up
def _gen_axes_patch(self):
        return Circle((0.5, 0.5), 0.5) 
Example 56
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_mixed_collection():
    from matplotlib import patches
    from matplotlib import collections

    x = list(range(10))

    # First illustrate basic pyplot interface, using defaults where possible.
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    c = patches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')

    # PDF can optimize this one
    p1 = collections.PatchCollection([c], match_original=True)
    p1.set_offsets([[0, 0], [24, 24]])
    p1.set_linewidths([1, 5])

    # PDF can't optimize this one, because the alpha of the edge changes
    p2 = collections.PatchCollection([c], match_original=True)
    p2.set_offsets([[48, 0], [-32, -16]])
    p2.set_linewidths([1, 5])
    p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])

    ax.patch.set_color('0.5')
    ax.add_collection(p1)
    ax.add_collection(p2)

    ax.set_xlim(0, 16)
    ax.set_ylim(0, 16) 
Example 57
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_image.py    MIT License 5 votes vote down vote up
def test_image_clip():
    d = [[1, 2], [3, 4]]

    fig, ax = plt.subplots()
    im = ax.imshow(d)
    patch = patches.Circle((0, 0), radius=1, transform=ax.transData)
    im.set_clip_path(patch) 
Example 58
Project: triplet-loss   Author: conan7882   File: viz.py    MIT License 5 votes vote down vote up
def viz_embedding(embedding, labels, save_dir):
            
    labels = labels.astype(int)
    classes = set(labels)

    plt.figure()
    kwargs = {'alpha': 0.8}
    colormap = plt.cm.rainbow(np.linspace(0, 1, len(classes)))
    kwargs['c'] = [colormap[i] for i in labels]

    # make room for legend
    ax = plt.subplot(111, aspect='equal')
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    handles = [mpatches.Circle((0,0), label=class_, color=colormap[i])
                for i, class_ in enumerate(classes)]
    ax.legend(handles=handles, shadow=True, bbox_to_anchor=(1.05, 0.45),
              fancybox=True, loc='center left')


    plt.scatter(embedding[:,0], embedding[:,1], s=2, **kwargs)
    plt.savefig(save_dir, bbox_inches="tight")
    plt.close()

# def tensorboard_embedding(embedding, writer):
#     from tensorflow.contrib.tensorboard.plugins import projector

#     config = projector.ProjectorConfig()
#     embedding = config.embeddings.add()
#     embedding.tensor_name = embedding_var.name 
Example 59
Project: Buffe   Author: bentzinir   File: ctrlr_optimizer.py    MIT License 5 votes vote down vote up
def _print_junction(self):
        bw = self.game_params['board_width']
        lw = self.game_params['lane_width']

        # road marks
        plt.vlines(lw, -bw, -lw)
        plt.vlines(-lw, -bw, -lw)
        plt.vlines(-lw, lw, bw)
        plt.vlines(lw, lw, bw)
        plt.hlines(-lw, -bw, -lw)
        plt.hlines(-lw, lw, bw)
        plt.hlines(lw, -bw, -lw)
        plt.hlines(lw, lw, bw)

        # lane marks
        plt.vlines(0, -bw, -lw, linestyles='dashed')
        plt.vlines(0, lw, bw, linestyles='dashed')
        plt.hlines(0, -bw, -lw, linestyles='dashed')
        plt.hlines(0, lw, bw, linestyles='dashed')

        # stopping lines
        plt.hlines(-lw, 0, lw, linestyles='solid')
        plt.hlines(-lw-0.01, 0, lw, linestyles='solid')

        plt.hlines(lw, -lw, 0, linestyles='solid')
        plt.hlines(lw+0.01, -lw, 0, linestyles='solid')

        plt.vlines(-lw, -lw, 0, linestyles='solid')
        plt.vlines(-lw-0.01, -lw, 0, linestyles='solid')

        plt.vlines(lw, 0, lw, linestyles='solid')
        plt.vlines(lw+0.01, 0, lw, linestyles='solid')

        # print rails
        # self.ax.add_patch(Circle(xy=(lw,-lw), radius=lw/2, edgecolor='k', facecolor='none'))
        # self.ax.add_patch(Circle(xy=(-lw,-lw), radius=3*lw/2, edgecolor='k', facecolor='none')) 
Example 60
Project: Taller-PyConEs-2015   Author: AeroPython   File: nash.py    MIT License 5 votes vote down vote up
def plot_world (world):
    '''
    This function takes a numpy 2D array with string elements 
    and scatters it with the colours corresponding to these strings
    '''
    
    #This sets the colours for the plot
    cmap = plt.cm.jet
    world = world*160 + 90

    
    fig = plt.figure(figsize = (10,10))
    ax = fig.add_subplot(111, aspect='equal')
        
    for ii in range (world.shape[0]):
        
        x = range(world.shape[1])
        y = world.shape[1] * [ii]
        colours = world [ii]
        
        for (x, y, c) in zip(x, y, colours):
            ax.add_artist(Circle(xy=(x, y), radius=0.45, color=cmap(c)))
        
    plt.axis('off')
    ax.set_xlim(-1, world.shape[1])
    ax.set_ylim(-1, world.shape[0]) 
Example 61
Project: IAGT   Author: saeedghsh   File: myCanvasLib.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plotCirc(self, circ, idx=None):
        [cx,cy,r] = circ
        # colors = 100*np.random.rand(len(self.patches))
        collection = PatchCollection([mpatches.Circle(np.array([cx,cy]),
                                                      r, ec="none")],
                                     alpha=self.AnnotationAlpha)
        # collection.set_array(np.array(colors))
        self.axes.add_collection(collection)

        if idx is not None:
            self.axes.text(cx,cy, str(idx) , fontsize=15)

        self.draw() 
Example 62
Project: scalable-irl   Author: makokal   File: social_navigation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _btn_click(self, event):
        if self._recording:
            self.new_demo.append([event.xdata, event.ydata])
            cc = self.demo_color
            self.ax.add_artist(Circle((event.xdata, event.ydata),
                               0.03, fc=cc, ec=cc))
            self.figure.canvas.draw() 
Example 63
Project: scalable-irl   Author: makokal   File: puddle_world.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _btn_press(self, event):
        if self._recording:
            self.new_demo.append([event.xdata, event.ydata])
            cc = self.demo_color
            self.ax.add_artist(Circle((event.xdata, event.ydata),
                               0.005, fc=cc, ec=cc))
            self.figure.canvas.draw() 
Example 64
Project: funzo   Author: makokal   File: chainworld.py    MIT License 5 votes vote down vote up
def _plot_world(self, ax):
        for s in self.states:
            loc = (s + 1, 2)
            face = 'gray' if self.terminal(s) else 'w'
            ax.add_artist(Circle(loc, radius=0.3, color=face,
                          ec='r', lw=1.5, aa=True))
            text = 's' + str(s + 1)
            ax.text(loc[0], loc[1], text, ha="center", size=14)

        ax.set_xlim([0, len(self.states) + 1])
        ax.set_ylim([1, 3])
        ax.set_xticks([])
        ax.set_yticks([])
        return ax 
Example 65
Project: BorderPeelingClustering   Author: nadavbar   File: clustering_tools.py    MIT License 5 votes vote down vote up
def add_circles(self, ax, centers, radis):
        circles = []
        for c, r in zip(centers, radis):
            circles.append(patches.Circle(tuple(c), r))

        patch_collection = PatchCollection(circles)
        patch_collection.set_facecolor("none")
        patch_collection.set_edgecolor("blue")
        patch_collection.set_linewidth(1.5)
        patch_collection.set_linestyle("dashed")
        ax.add_collection(patch_collection)
        print "added %d circles"%len(circles) 
Example 66
Project: pyplis   Author: jgliss   File: doascalib.py    GNU General Public License v3.0 4 votes vote down vote up
def plot(self, ax=None):
        """Draw the current FOV position into the current correlation img."""
        if ax is None:
            fig, ax = subplots(1, 1, figsize=(12, 8))
        else:
            fig = ax.figure
        img = self.corr_img.img
        vmin, vmax = img.min(), img.max()
        cmap = shifted_color_map(vmin, vmax, cmap=RdBu)
        h, w = img.shape
        disp = ax.imshow(img, vmin=vmin, vmax=vmax, cmap=cmap)
        cb = fig.colorbar(disp, ax=ax, shrink=0.9)
        cx, cy = self.pixel_position_center(1)
        if self.method == "ifr":
            popt = self.popt
            cb.set_label(r"FOV fraction [$10^{-2}$ pixel$^{-1}$]")

            xgrid, ygrid = mesh_from_img(img)
            if len(popt) == 7:
                ell = Ellipse(xy=(popt[1], popt[2]), width=popt[3],
                              height=popt[3] / popt[4], color="k", lw=2,
                              fc="lime", alpha=.5)
            else:
                ell = Ellipse(xy=(popt[1], popt[2]), width=popt[3],
                              height=popt[3] / popt[4], angle=popt[7],
                              color="k", lw=2, fc="lime", alpha=.5)

            ax.add_artist(ell)
            ax.axhline(self.cy_rel, ls="--", color="k")
            ax.axvline(self.cx_rel, ls="--", color="k")

            ax.get_xaxis().set_ticks([0, self.cx_rel, w])
            ax.get_yaxis().set_ticks([0, self.cy_rel, h])

            # ax.set_axis_off()
            ax.set_title(r"Corr img (IFR), pos abs (x,y): (%d, %d), "
                         "lambda=%.1e"
                         % (cx, cy, self.search_settings["ifrlbda"]))

        elif self.method == "pearson":
            cb.set_label(r"Pearson corr. coeff.")
            ax.autoscale(False)

            c = Circle((self.cx_rel, self.cy_rel), self.radius_rel, ec="k",
                       lw=2, fc="lime", alpha=.5)
            ax.add_artist(c)
            ax.set_title("Corr img (pearson), pos abs (x,y): (%d, %d)"
                         % (cx, cy))
            ax.get_xaxis().set_ticks([0, self.cx_rel, w])
            ax.get_yaxis().set_ticks([0, self.cy_rel, h])
            ax.axhline(self.cy_rel, ls="--", color="k")
            ax.axvline(self.cx_rel, ls="--", color="k")
        ax.set_xlabel("Pixel row")
        ax.set_ylabel("Pixel column")
        return ax 
Example 67
Project: peri   Author: peri-source   File: plots.py    MIT License 4 votes vote down vote up
def twoslice_overlay(s, zlayer=None, xlayer=None, size=6.0,
        cmap='bone_r', vmin=0, vmax=1, showimage=False, solid=False, pad=None):
    pad = pad or s.pad
    trim = (np.s_[pad:-pad],)*3
    field = s.image[trim]

    slicez = zlayer or field.shape[0]//2
    slicex = xlayer or field.shape[2]//2
    slicer1 = np.s_[slicez,:,:]
    slicer2 = np.s_[:,:,slicex]

    sh = field.shape
    q = float(sh[1]) / (sh[0]+sh[1])
    r = float(sh[1] + sh[0]) / sh[1]

    fig = pl.figure(figsize=(size, size*r*1.05))
    ax1 = fig.add_axes((0, 1-q, 1, q))
    ax2 = fig.add_axes((0, 0, 1, 1-q))

    mu = s.state.copy()
    active = np.arange(s.N)[s.state[s.b_typ]==1.]

    pos = mu[s.b_pos].reshape(-1,3)[active]
    rad = mu[s.b_rad][active]

    def show(ax, slicer):
        talpha = 0.0 if not showimage else 1.0
        ax.imshow(field[slicer], cmap=cmap, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=talpha)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_axis_bgcolor('black')
        ax.grid('off')

    def circles(ax, layer, axis):
        # get the index of the particles we want to include
        talpha = 1.0 if not showimage else 0.8
        cedge = 'white' if not showimage else 'black'
        cface = 'white' if solid else 'none'
        particles = np.arange(len(pos))[np.abs(pos[:,axis] - layer) < rad]

        # for each of these particles display the effective radius
        # in the proper place
        for i in particles:
            p = pos[i].copy()
            r = 2*np.sqrt(rad[i]**2 - (p[axis] - layer)**2)
            if axis==0:
                c = Circle((p[2]-pad,p[1]-pad), radius=r/2, fc=cface, ec=cedge, alpha=talpha)
            if axis==2:
                c = Circle((p[1]-pad,p[0]-pad), radius=r/2, fc=cface, ec=cedge, alpha=talpha)
            ax.add_patch(c)

    show(ax1, slicer1)
    show(ax2, slicer2)

    circles(ax1, slicez+pad, 0)
    circles(ax2, slicex+pad, 2) 
Example 68
Project: peri   Author: peri-source   File: plots.py    MIT License 4 votes vote down vote up
def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):
    """
    Plots a set of circles corresponding to a slice through the platonic
    structure. Copied from twoslice_overlay with comments, standaloneness.

    Inputs
    ------
        pos : array of particle positions; [N,3]
        rad : array of particle radii; [N]
        ax : plt.axis instance
        layer : Which layer of the slice to use.
        axis : The slice of the image, 0, 1, or 2.
        cedge : edge color
        cface : face color
        talpha : Alpha of the thing
    """
    pos = st.obj_get_positions()
    rad = st.obj_get_radii()
    shape = st.ishape.shape.tolist()
    shape.pop(axis) #shape is now the shape of the image
    if ax is None:
        fig = plt.figure()
        axisbg = 'white' if cface == 'black' else 'black'
        sx, sy = ((1,shape[1]/float(shape[0])) if shape[0] > shape[1] else
                (shape[0]/float(shape[1]), 1))
        ax = fig.add_axes((0,0, sx, sy), axisbg=axisbg)
    # get the index of the particles we want to include
    particles = np.arange(len(pos))[np.abs(pos[:,axis] - layer) < rad]

    # for each of these particles display the effective radius
    # in the proper place
    scale = 1.0 #np.max(shape).astype('float')
    for i in particles:
        p = pos[i].copy()
        r = 2*np.sqrt(rad[i]**2 - (p[axis] - layer)**2)
        #CIRCLE IS IN FIGURE COORDINATES!!!
        if axis==0:
            ix = 1; iy = 2
        elif axis == 1:
            ix = 0; iy = 2
        elif axis==2:
            ix = 0; iy = 1
        c = Circle((p[ix]/scale, p[iy]/scale), radius=r/2/scale, fc=cface,
                ec=cedge, alpha=talpha)
        ax.add_patch(c)
    # plt.axis([0,1,0,1])
    plt.axis('equal') #circles not ellipses
    return ax 
Example 69
Project: fanalysis   Author: OlivierGarciaDev   File: pca.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def correlation_circle(self, num_x_axis, num_y_axis, figsize=None):
        """ Plot the correlation circle
        
        Parameters
        ----------
        num_x_axis : int
            Select the component to plot as x axis.
        
        num_y_axis : int
             Select the component to plot as y axis.
        
        figsize : tuple of integers or None
            Width, height of the figure in inches.
            If not provided, defaults to rc figure.figsize

        Returns
        -------
        None
        """
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111, aspect="equal")
        ax.add_artist(patches.Circle((0, 0), 1.0, color="black", fill=False))
        
        x_serie = self.col_cor_[:, num_x_axis - 1]
        y_serie = self.col_cor_[:, num_y_axis - 1]
        labels = self.col_labels_
        
        for i in np.arange(0, x_serie.shape[0]):
            x = x_serie[i]
            y = y_serie[i]
            label = labels[i]
            delta = 0.1 if y >= 0 else -0.1
            ax.annotate("", xy=(x, y), xytext=(0, 0),
                        arrowprops={"facecolor": "black",
                                    "width": 1,
                                    "headwidth": 4})
            ax.text(x, y + delta, label,
                    horizontalalignment="center", verticalalignment="center",
                    color="blue")
        
        plt.axvline(x=0, linestyle="--", linewidth=0.5, color="k")
        plt.axhline(y=0, linestyle="--", linewidth=0.5, color="k")
        ax.set_xlim(-1.3, 1.3)
        ax.set_ylim(-1.3, 1.3)
        plt.title("Correlation circle")
        plt.xlabel("Dim " + str(num_x_axis) + " ("
                    + str(np.around(self.eig_[1, num_x_axis - 1], 2)) + "%)")
        plt.ylabel("Dim " + str(num_y_axis) + " ("
                    + str(np.around(self.eig_[1, num_y_axis - 1], 2)) + "%)")
        plt.show() 
Example 70
Project: AAE-tensorflow   Author: gitmatti   File: plot.py    GNU General Public License v3.0 4 votes vote down vote up
def plot_encoding(model, sess, title=None, name="encoding",
                  datasets=("test","validation"), range_=(-4.,4.),
                  save=True, outdir="./plots", **kwargs):
    """
    Plotting utility to encode dataset images in (low dimensional!) latent space
    """
    # TODO: check for 2d
    title = (title if title else name)
    for dataset_name in datasets:
        dataset = getattr(model.dataset, dataset_name)
        feed_dict = {model.x_in_test: dataset.images}
        encoding = sess.run(model.z_dist_info_, feed_dict=feed_dict)
        centers = encoding[model.latent_dist.dist_info_keys[0]]
        ys, xs = centers.T

        plt.figure()
        plt.title("round {}: {} in latent space".format(model.counter,
                                                        dataset_name))
        kwargs = {'alpha': 0.8}

        classes = set(dataset.labels)
        if classes:
            colormap = plt.cm.rainbow(np.linspace(0, 1, len(classes)))
            kwargs['c'] = [colormap[i] for i in dataset.labels]
            # make room for legend
            ax = plt.subplot(111)
            box = ax.get_position()
            ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
            handles = [mpatches.Circle((0,0), label=class_, color=colormap[i])
                        for i, class_ in enumerate(classes)]
            ax.legend(handles=handles, shadow=True, bbox_to_anchor=(1.05, 0.45),
                      fancybox=True, loc='center left')

        plt.scatter(xs, ys, **kwargs)

        # map range_ to standard deviations of the target distribution
        stddev = model.target_dist.stddev
        adjusted_range = (stddev*range_[0], stddev*range_[1])

        if range_:
            plt.xlim(adjusted_range)
            plt.ylim(adjusted_range)

        if save:
            title = "{}_encoding_{}_round_{}.png".format(
                model.datetime, dataset_name, model.counter)
            plt.savefig(os.path.join(outdir, title), bbox_inches="tight")
        plt.close() 
Example 71
Project: lost   Author: l3p-cv   File: vis.py    MIT License 4 votes vote down vote up
def vis_tracks(img, tracks, frame_n, dots=15, figsize=(10,10), dot_radius=5, linewidth=2):
    '''Visualize a track on image
    
    Args:
        img (array or str): An RGB image or path to the image file.
        tracks (array): [[frame_n, track_id, xc, yc, w, h]...[...]]
            Box is defined relative to the image.
        frame_n (int): The frame number belonning to the image
        dots (int): Number of dots that will be displayed.
            Past locations that will be visualized.
        figsize (tuple): (int,int) Size of the figure to display.
        dot_radius (int): Radius of the first dot.
        linewidth (int): Linewidth of the box to draw.
    Returns:
        Matplotlib figure
    '''
    if type(img) == str:
        my_img = skimage.io.imread(img)
    else:
        my_img = img
    fig,ax = plt.subplots(1, figsize=figsize)
    ax.imshow(my_img)
    for track_id in np.unique(tracks[:,1]):
    #for track_id in [0]:
        dot_color = plt.cm.tab10(((track_id)%11)/10)
        #print('dot_color', dot_color)
        #print(track_id)
        track = tracks[tracks[:,1]==track_id]
        boxes = track[track[:,0]<=frame_n]
        #reverse boxes order 
        boxes = np.flip(boxes, 0)
        # if object is still present in current frame
        #if boxes.size > 0 and boxes[0][0] == frame_n:
        #print('boxes', boxes[0])
        for i, box in enumerate(boxes):
            if box.size > 0:
                #print(box)
                x = box[2] * img.shape[1]
                y = box[3] * img.shape[0]
                w = box[4] * img.shape[1]
                h = box[5] * img.shape[0]
                if i == 0 and box[0] == frame_n:
                    #print('original box', box)
                    #print('drawn box',(x-w/2,y-h/2,w,h))
                    bbox = patches.Rectangle((x-w/2,y-h/2),w,h,linewidth=linewidth,edgecolor=dot_color,facecolor='none')
                    ax.add_patch(bbox)
                #print('dot_color',dot_color)
                #dot = patches.Circle((x, y), radius=dot_radius-(dot_radius/dots)*i, color=dot_color)
                dot = patches.Circle((x, y), radius=dot_radius* 1.0/(frame_n+1-box[0]), color=dot_color, alpha=0.8)
                #dot = patches.Circle((x, y), radius=dot_radius , color=dot_color, alpha=1.0/(box[0]+1 - frame_n))
                ax.add_patch(dot)
                if (i+1) >= dots:
                    break
    return fig 
Example 72
Project: ml-five   Author: splendor-kill   File: main.py    MIT License 4 votes vote down vote up
def __init__(self):
        size = Board.BOARD_SIZE

        keymap = [k for k in plt.rcParams.keys() if k.startswith('keymap.')]
        for k in keymap:
            plt.rcParams[k] = ''

        self.fig = plt.figure(figsize=((size + 1) / 2.54, (size + 1) / 2.54), facecolor='#FFE991')
        self.fig.canvas.set_window_title('Training')
        span = 1. / (size + 1)
        self.ax = self.fig.add_axes((span, span, (size - 1) * span, (size - 1) * span),
                                    aspect='equal',
                                    axis_bgcolor='none',
                                    xticks=range(size),
                                    yticks=range(size),
                                    xticklabels=[chr(ord('A') + i) for i in range(size)],
                                    yticklabels=range(1, 1 + size))
        self.ax.grid(color='k', linestyle='-', linewidth=1)
        self.ax.set_title('press T for training')

        self.black_stone = patches.Circle((0, 0), .45,
                                          facecolor='#131814', edgecolor=(.8, .8, .8, 1),
                                          linewidth=2, clip_on=False, zorder=10)
        self.white_stone = copy.copy(self.black_stone)
        self.white_stone.set_facecolor('#FCF5F4')
        self.white_stone.set_edgecolor((.5, .5, .5))

        self.fig.canvas.mpl_connect('key_press_event', self._key_press)
        self.fig.canvas.mpl_connect('close_event', self._handle_close)
#         self.fig.canvas.mpl_connect('button_press_event', self._button_press)

        self.state = Gui.STATE_IDLE
        self.strategy_1 = None
        self.strategy_2 = None
        self.game = None
        self.all_stones = []
        self.oppo_pool = []
        self.msg_queue = queue.Queue(maxsize=100)

        self.timer = self.fig.canvas.new_timer(interval=50)
        self.timer.add_callback(self.on_update)
        self.timer.start()

        plt.show() 
Example 73
Project: calin   Author: sguiz   File: dnaplotlib.py    MIT License 4 votes vote down vote up
def sbol_origin (ax, type, num, start, end, prev_end, scale, linewidth, opts):
    """ Built-in SBOL origin renderer.
    """
    # Default options
    zorder_add = 0.0
    color = (0,0,0)
    start_pad = 2.0
    end_pad = 2.0
    x_extent = 10.0
    y_extent = 10.0
    linestyle = '-'
    # Reset defaults if provided
    if opts != None:
        if 'zorder_add' in list(opts.keys()):
            zorder_add = opts['zorder_add']
        if 'color' in list(opts.keys()):
            color = opts['color']
        if 'start_pad' in list(opts.keys()):
            start_pad = opts['start_pad']
        if 'end_pad' in list(opts.keys()):
            end_pad = opts['end_pad']
        if 'x_extent' in list(opts.keys()):
            x_extent = opts['x_extent']
        if 'y_extent' in list(opts.keys()):
            y_extent = opts['y_extent']
        if 'linestyle' in list(opts.keys()):
            linestyle = opts['linestyle']
        if 'linewidth' in list(opts.keys()):
            linewidth = opts['linewidth']
        if 'scale' in list(opts.keys()):
            scale = opts['scale']
    # Check direction add start padding
    final_end = end
    final_start = prev_end
    
    start = prev_end+start_pad
    end = start+x_extent
    final_end = end+end_pad
    ori_center = (start+((end-start)/2.0),0)
    
    c1 = Circle(ori_center, x_extent/2.0, linewidth=linewidth, edgecolor=color, 
                facecolor=(1,1,1), zorder=12+zorder_add)
    
    ax.add_patch(c1)
    
    if opts != None and 'label' in list(opts.keys()):
        if final_start > final_end:
            write_label(ax, opts['label'], final_end+((final_start-final_end)/2.0), opts=opts)
        else:
            write_label(ax, opts['label'], final_start+((final_end-final_start)/2.0), opts=opts)

    if final_start > final_end:
        return prev_end, final_start
    else:
        return prev_end, final_end 
Example 74
Project: dsp-labs   Author: LCAV   File: plot_zplane.py    MIT License 4 votes vote down vote up
def zplane(b,a):
    """Plot the complex z-plane given a transfer function.
    """

    # get a figure/plot
    ax = plt.subplot(111)

    # create the unit circle
    uc = patches.Circle((0,0), radius=1, fill=False,
                        color='black', ls='dashed')
    ax.add_patch(uc)

    # The coefficients are less than 1, normalize the coeficients
    if np.max(b) > 1:
        kn = np.max(b)
        b = b/float(kn)
    else:
        kn = 1

    if np.max(a) > 1:
        kd = np.max(a)
        a = a/float(kd)
    else:
        kd = 1
        
    # Get the poles and zeros
    p = np.roots(a)
    z = np.roots(b)
    k = kn/float(kd)
    
    # Plot the zeros and set marker properties    
    t1 = plt.plot(z.real, z.imag, 'go', ms=10, label="Zeros")
    plt.setp( t1, markersize=10.0, markeredgewidth=1.0,
              markeredgecolor='k', markerfacecolor='g')

    # Plot the poles and set marker properties
    t2 = plt.plot(p.real, p.imag, 'rx', ms=10, label="Poles")
    plt.setp( t2, markersize=12.0, markeredgewidth=3.0,
              markeredgecolor='r', markerfacecolor='r')

    ax.spines['left'].set_position('center')
    ax.spines['bottom'].set_position('center')
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    # set the ticks
    r = 1.5; plt.axis('scaled'); plt.axis([-r, r, -r, r])
    ticks = [-1, -.5, .5, 1]; plt.xticks(ticks); plt.yticks(ticks)

    plt.legend()
    

    return z, p, k 
Example 75
Project: paper-flowmap-code   Author: caesar0301   File: utils.py    GNU General Public License v3.0 4 votes vote down vote up
def draw_network(G, pos, ax):
    """Draw network with curved edges.

    Examples
    --------

    plt.figure(figsize=(10, 10))
    ax=plt.gca()
    pos=nx.spring_layout(G)
    draw_network(G, pos, ax)
    ax.autoscale()
    plt.axis('equal')
    plt.axis('off')
    plt.title('Curved network')

    """
    # ax=plt.gca()
    # pos=nx.spring_layout(motif)
    # draw_network(motif, pos, ax)


    for n in G:
        c = Circle(pos[n], radius=0.05, alpha=0.5)
        ax.add_patch(c)
        G.node[n]['patch'] = c
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1 = G.node[u]['patch']
        n2 = G.node[v]['patch']
        rad = 0.1
        if (u,v) in seen:
            rad = seen.get((u,v))
            rad = (rad + np.sign(rad) * 0.1) * -1
        alpha = 0.5; color = 'k'
        e = FancyArrowPatch(n1.center, n2.center,
                            patchA=n1, patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=%s' % rad,
                            mutation_scale=10.0,
                            lw=2, alpha=alpha, color=color)
        seen[(u, v)] = rad
        ax.add_patch(e)

    # ax.autoscale()
    # plt.axis('equal')
    # plt.axis('off')

    return e 
Example 76
Project: scalable-irl   Author: makokal   File: social_navigation.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def visualize(self, G, policies, fsize=(12, 9),
                  show_edges=False, show_waypoints=False,
                  recording=False):
        """ Visualize the social navigation world

        Allows recording of demonstrations and also display of final
        graph representing the MDP
        """
        self._setup_visuals(fsize)

        for _, p in self._world.persons.items():
            phead = np.degrees(np.arctan2(p[3], p[2]))
            self.ax.add_artist(Ellipse((p[0], p[1]), width=0.3, height=0.6,
                               angle=phead, color='r', fill=False, lw=1.5,
                               aa=True, zorder=3))
            self.ax.add_artist(Circle((p[0], p[1]), radius=0.12, color='w',
                               ec='r', lw=2.5, aa=True, zorder=3))
            self.ax.arrow(p[0], p[1], p[2]/5., p[3]/5., fc='r', ec='r', lw=1.5,
                          head_width=0.14, head_length=0.1, zorder=3)

            # speed = np.hypot(p[2], p[3])
            # hz = speed * 0.55
            # self.ax.add_artist(Circle((p[0], p[1]), radius=hz, color='r',
            #                    ec='r', lw=1, aa=True, alpha=0.2))

        for [i, j] in self._world.relations:
            x1, y1 = self._world.persons[i][0], self._world.persons[i][1]
            x2, y2 = self._world.persons[j][0], self._world.persons[j][1]
            self.ax.plot((x1, x2), (y1, y2), ls='-', c='r', lw=2.0, zorder=2)

        if recording:
            g = G.mdp.goal_state
            starts = G.mdp.start_states
            self.ax.add_artist(Circle((g[0], g[1]), 1.5/10., fc='g',
                               ec='g', lw=1.5, zorder=3))

            for s in starts:
                self.ax.add_artist(Circle((s[0], s[1]), 1.5/10., fc='k',
                                   ec='k', lw=1.5, zorder=3))

            return self.ax

        self._plot_graph_in_world(G, policies, show_edges, show_waypoints)

        return self.ax

    # -------------------------------------------------------------
    # internals
    # ------------------------------------------------------------- 
Example 77
Project: scalable-irl   Author: makokal   File: puddle_world.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _setup_visuals(self):
        """Setup visual elements
        """
        self.figure = plt.figure(figsize=(12, 9))
        self.ax = plt.axes([0, 0, 0.8, 1])
        self.figure.add_axes(self.ax)

        self.record_status = self.figure.text(0.825, 0.3, 'Recording [OFF]',
                                              fontsize=14, color='blue')
        self.figure.text(0.825, 0.2, '#Demos: ', fontsize=10)
        self.demo_count = self.figure.text(0.925, 0.2, '0', fontsize=10)
        # catch events
        self.figure.canvas.mpl_connect('key_press_event', self._key_press)
        self.figure.canvas.mpl_connect('button_press_event', self._btn_press)

        # Main rectangle showing the environment
        self.ax.add_artist(Rectangle((0, 0), width=1, height=1, color='c',
                           zorder=0, ec='k', lw=8, fill=False))

        # draw goal region
        points = [[1, 1], [1, 0.95], [0.95, 1]]
        goal_polygon = plt.Polygon(points, color='green')
        self.ax.add_patch(goal_polygon)

        # draw puddles
        x1 = self._world.puddles[0].start[0]
        y1 = self._world.puddles[0].start[1]-0.05
        width = self._world.puddles[0].length
        height = self._world.puddles[1].length
        pd1 = Rectangle((x1, y1), height=0.1, width=width,
                        color='brown', alpha=0.7, aa=True, lw=0)
        self.ax.add_artist(pd1)
        self.ax.add_artist(Wedge(self._world.puddles[0].start, 0.05, 90, 270,
                           fc='brown', alpha=0.7, aa=True, lw=0))
        self.ax.add_artist(Wedge(self._world.puddles[0].end, 0.05, 270, 90,
                           fc='brown', alpha=0.7, aa=True, lw=0))

        x2 = self._world.puddles[1].start[0]-0.05
        y2 = self._world.puddles[1].start[1]
        pd2 = Rectangle((x2, y2), width=0.1, height=height,
                        color='brown', alpha=0.7)
        self.ax.add_artist(pd2)
        self.ax.add_artist(Wedge(self._world.puddles[1].start, 0.05, 180, 360,
                           fc='brown', alpha=0.7, aa=True, lw=0))
        self.ax.add_artist(Wedge(self._world.puddles[1].end, 0.05, 0, 180,
                           fc='brown', alpha=0.7, aa=True, lw=0))

        # draw the agent at initial pose
        robot_start = (0.3, 0.65)
        robot_visual = Circle(robot_start, 0.01, fc='b', ec='k', zorder=3)
        self.ax.add_artist(robot_visual)
        self.robot = Agent(position=robot_start, orientation=(1, 1),
                           visual=robot_visual)
        self.ax.set_xlim([0, 1])
        self.ax.set_ylim([0, 1])
        self.ax.set_xticks([])
        self.ax.set_yticks([]) 
Example 78
Project: scalable-irl   Author: makokal   File: puddle_world.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _plot_graph_in_world(self, G, policies, show_edges):
        """ Shows the lattest version of the world with MDP
        """
        gna = G.gna
        values = [gna(n, 'V') for n in G.nodes]
        nv = mpl.colors.Normalize(vmin=min(values), vmax=max(values))
        cmapping = cm.ScalarMappable(norm=nv, cmap=cm.viridis)

        best_nodes = set()
        for traj in policies:
            for state in traj:
                best_nodes.add(state)

        for i, n in enumerate(G.nodes):
            posx, posy = gna(n, 'data')
            if gna(n, 'type') == 'start':
                color = 'black'
                nr = 1.0
            elif self.terminal((posx, posy)):
                color = 'green'
                nr = 1.5
            elif n in best_nodes:
                color = 'green'
                nr = 0.5
            else:
                color = cmapping.to_rgba(gna(n, 'V'))
                nr = 0.5
            self.ax.add_artist(Circle((posx, posy), nr/100., fc=color,
                               ec=color, lw=1.5, zorder=3))

            p = gna(n, 'pi')
            ndata = gna(n, 'data')
            for i, e in enumerate(G.out_edges(n)):
                tdata = gna(e[1], 'data')
                x1, y1 = ndata[0], ndata[1]
                x2, y2 = tdata[0], tdata[1]

                if n in best_nodes and i == p:
                    self.ax.plot((x1, x2), (y1, y2), ls='-',
                                 lw=2.0, c='g', zorder=3)
                else:
                    if show_edges:
                        self.ax.plot((x1, x2), (y1, y2), ls='-', lw=1.0,
                                     c='0.7', alpha=0.5)

######################################################################## 
Example 79
Project: funzo   Author: makokal   File: puddleworld.py    MIT License 4 votes vote down vote up
def _setup_visuals(self, ax):
        """Setup visual elements
        """
        # Main rectangle showing the environment
        ax.add_artist(Rectangle((0, 0), width=1, height=1, color='c',
                                zorder=0, ec='k', lw=8, fill=False))

        # draw goal region
        points = [[1, 1], [1, 0.95], [0.95, 1]]
        goal_polygon = plt.Polygon(points, color='green')
        ax.add_patch(goal_polygon)

        # draw puddles
        x1 = self.puddles[0].start[0]
        y1 = self.puddles[0].start[1] - 0.05
        width = self.puddles[0].length
        height = self.puddles[1].length
        pd1 = Rectangle((x1, y1), height=0.1, width=width,
                        color='brown', alpha=0.7, aa=True, lw=0)
        ax.add_artist(pd1)
        ax.add_artist(Wedge(self.puddles[0].start, 0.05, 90, 270,
                            fc='brown', alpha=0.7, aa=True, lw=0))
        ax.add_artist(Wedge(self.puddles[0].end, 0.05, 270, 90,
                            fc='brown', alpha=0.7, aa=True, lw=0))

        x2 = self.puddles[1].start[0] - 0.05
        y2 = self.puddles[1].start[1]
        pd2 = Rectangle((x2, y2), width=0.1, height=height,
                        color='brown', alpha=0.7)
        ax.add_artist(pd2)
        ax.add_artist(Wedge(self.puddles[1].start, 0.05, 180, 360,
                            fc='brown', alpha=0.7, aa=True, lw=0))
        ax.add_artist(Wedge(self.puddles[1].end, 0.05, 0, 180,
                            fc='brown', alpha=0.7, aa=True, lw=0))

        # draw the agent at initial pose
        robot_start = self._start  # (0.3, 0.65)
        robot_visual = Circle(robot_start, 0.01, fc='b', ec='k', zorder=3)
        ax.add_artist(robot_visual)
        self.robot = Agent(position=robot_start, orientation=(1, 1),
                           visual=robot_visual)
        ax.set_xlim([0, 1])
        ax.set_ylim([0, 1])
        ax.set_xticks([])
        ax.set_yticks([])

        return ax 
Example 80
Project: funzo   Author: makokal   File: nav_world.py    MIT License 4 votes vote down vote up
def visualize(self, ax, **kwargs):
        """ Visualize the social navigation scene """
        # if self._persons is None:
        #     warnings.warn('No entities to visualize!')
        #     return ax

        if self._persons is not None:
            for _, p in self._persons.items():
                phead = np.degrees(np.arctan2(p[3], p[2]))
                ax.add_artist(Ellipse((p[0], p[1]), width=0.3, height=0.6,
                                      angle=phead, color='r', fill=False,
                                      lw=1.5, aa=True, zorder=3))
                ax.add_artist(Circle((p[0], p[1]), radius=0.12, color='w',
                                     ec='r', lw=2.5, aa=True, zorder=3))
                ax.arrow(p[0], p[1], p[2] / 5., p[3] / 5., fc='r', ec='r',
                         lw=1.5, head_width=0.14, head_length=0.1, zorder=3)

            if self._groups is not None:
                for (i, j) in self._groups:
                    x1, y1 = self._persons[i][0], self._persons[i][1]
                    x2, y2 = self._persons[j][0], self._persons[j][1]
                    ax.plot((x1, x2), (y1, y2), ls='-', c='r', lw=2.0,
                            zorder=2)

        if 'graph' in kwargs:
            G = kwargs['graph']

            for i, n in enumerate(G.nodes):
                posx, posy, _ = G.gna(n, 'data')
                if G.gna(n, 'type') == 'start':
                    color = 'black'
                    nr = 1.0
                elif self.terminal((posx, posy)):
                    color = 'green'
                    nr = 1.5
                else:
                    color = 'orange'
                    nr = 0.5
                ax.add_artist(Circle((posx, posy), nr / 10., fc=color,
                                     ec=color, lw=1.5, zorder=3))

            ndata = G.gna(n, 'data')
            for i, e in enumerate(G.out_edges(n)):
                tdata = G.gna(e[1], 'data')
                x1, y1 = ndata[0], ndata[1]
                x2, y2 = tdata[0], tdata[1]
                ax.plot((x1, x2), (y1, y2),
                        ls='-', lw=1.0, c='0.7', alpha=0.7)

        ax.set_xlim([self.x, self.w])
        ax.set_ylim([self.y, self.h])

        return ax