Example #1
0
def plot_source_locations(source_xs_0, source_ys_0, source_xs_120, source_ys_120, source_xs_90, source_ys_90,
                          damage_xs=[], damage_ys=[]):
    # center marks
    #source_xs = np.hstack((source_xs_0, source_xs_120, source_xs_90, damage_xs))
    #source_ys = np.hstack((source_ys_0, source_ys_120, source_ys_90, damage_ys))
    source_xs = np.hstack((source_xs_0, source_xs_120, source_xs_90))
    source_ys = np.hstack((source_ys_0, source_ys_120, source_ys_90))

    mark_radii = np.repeat(10, len(source_xs))
    mark_colors = np.repeat(5, len(source_xs))
    plt.scatter(source_xs, source_ys, s=mark_radii, c=mark_colors, cmap=cm.Set1, alpha=1.0)

    fig = plt.gcf()
    ax = fig.gca()
    error_radius = 2.9

    # error circles
    patches = []
    for coordinate in zip(source_xs_0,source_ys_0):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, cmap=cm.brg, norm=mpl.colors.Normalize(0.,1.), alpha=0.2)
    collection.set_array(np.repeat(0.5, len(source_xs_0)))
    ax.add_collection(collection)

    patches = []
    for coordinate in zip(source_xs_120,source_ys_120):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, cmap=cm.brg, norm=mpl.colors.Normalize(0.,1.), alpha=0.2)
    collection.set_array(np.repeat(1.0, len(source_xs_120)))
    ax.add_collection(collection)

    patches = []
    for coordinate in zip(source_xs_90,source_ys_90):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, cmap=cm.brg, norm=mpl.colors.Normalize(0.,1.), alpha=0.2)
    collection.set_array(np.repeat(0.0, len(source_xs_90)))
    ax.add_collection(collection)

    # damage marks
    patches = []
    for coordinate in zip(damage_xs,damage_ys):
        coordinate = np.array(coordinate)
        #patches.append(mpatches.RegularPolygon(coordinate, 5, 0.4))
        patches.append(mpatches.Rectangle(coordinate-[0.04,0.4], 0.08, 0.8))
        patches.append(mpatches.Rectangle(coordinate-[0.4,0.05], 0.8, 0.08))
    collection = mcollections.PatchCollection(patches, color='k', alpha=1.0)
    #collection.set_array(np.repeat(0.5, len(source_xs_0)))
    ax.add_collection(collection)


    # cavity
    origin_x = np.zeros(1)
    origin_y = np.zeros(1)
    cavity_radius = 10000
    #plt.scatter([0, 0], [0, 0], s=[90000, 0], c=[3,1], cmap=cm.Set1, alpha=0.1)
    cavity=plt.Circle((0,0),11.43,color='k',alpha=0.1)
    ax.add_artist(cavity)

    plt.xlim((-16, 16))
    plt.ylim((-16, 16))
def test_collection_transform_of_none():
    # tests the behaviour of collections added to an Axes with various
    # transform specifications

    ax = plt.axes()
    ax.set_xlim([1, 3])
    ax.set_ylim([1, 3])

    # draw an ellipse over data coord (2,2) by specifying device coords
    xy_data = (2, 2)
    xy_pix = ax.transData.transform_point(xy_data)

    # not providing a transform of None puts the ellipse in data coordinates
    e = mpatches.Ellipse(xy_data, width=1, height=1)
    c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5)
    ax.add_collection(c)
    # the collection should be in data coordinates
    assert c.get_offset_transform() + c.get_transform() == ax.transData

    # providing a transform of None puts the ellipse in device coordinates
    e = mpatches.Ellipse(xy_pix, width=120, height=120)
    c = mcollections.PatchCollection([e], facecolor='coral', alpha=0.5)
    c.set_transform(None)
    ax.add_collection(c)
    assert isinstance(c.get_transform(), mtransforms.IdentityTransform)

    # providing an IdentityTransform puts the ellipse in device coordinates
    e = mpatches.Ellipse(xy_pix, width=100, height=100)
    c = mcollections.PatchCollection([e],
                                     transform=mtransforms.IdentityTransform(),
                                     alpha=0.5)
    ax.add_collection(c)
    assert isinstance(c._transOffset, mtransforms.IdentityTransform)
Example #3
0
def plot_source_locations(predicted_xs, predicted_ys, actual_xs, actual_ys, error_radius=0.9, cavity_radius=14.22):
    # center marks
    source_xs = np.hstack((predicted_xs, actual_xs))
    source_ys = np.hstack((predicted_ys, actual_ys))

    mark_radii = np.repeat(10, len(predicted_xs))
    mark_colors = np.repeat(5, len(predicted_xs))
    plt.scatter(predicted_xs, predicted_ys, s=10, c='k', cmap=cm.Set1, alpha=1.0)

    fig = plt.gcf()
    ax = fig.gca()

    # error circles
    patches = []
    for coordinate in zip(predicted_xs,predicted_ys):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, color='k', alpha=0.2)
    collection.set_array(np.repeat(0.5, len(predicted_xs)))
    ax.add_collection(collection)

    # damage marks
    patches = []
    for coordinate in zip(actual_xs,actual_ys):
        patches.append(mpatches.RegularPolygon(coordinate, 5, 0.4))
    collection = mcollections.PatchCollection(patches, color='k', alpha=0.2)
    #collection.set_array(np.repeat(0.5, len(source_xs_0)))
    ax.add_collection(collection)


    # cavity
    cavity=plt.Circle((0,0),cavity_radius,color='k',alpha=0.1)
    ax.add_artist(cavity)

    plt.xlim((-16, 16))
    plt.ylim((-16, 16))
Example #4
0
def test_mixed_collection():
    from matplotlib import patches
    from matplotlib import collections

    x = 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)
def draw_graph(G):
    # lines = [[(2, -1), (2, 2), (5, 5), (5, 6), (3, 8)], [(4, 2), (4, 8)], [(1, 4), (5, 8)]]
    # c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])
    # lc = mc.LineCollection(lines, colors=c, linewidths=2)
    # fig, ax = pl.subplots()
    # ax.add_collection(lc)
    # ax.autoscale()
    # ax.margins(0.1)
    # pl.show()

    # lines = [[(2, -1), (2, 2), (5, 5), (5, 6), (3, 8)], [(4, 2), (4, 8)], [(1, 4), (5, 8)]]
    c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])

    lines = []
    for key in G.graph_streets:
        lines.append(list(G.graph_streets[key].points))

    edges = []
    for pair in G.edge:
        src = pair[0]
        dst = pair[1]
        pt1 = (G.vertex[src].x, G.vertex[src].y)
        pt2 = (G.vertex[dst].x, G.vertex[dst].y)
        edges.append([pt1, pt2])

    patches = []
    for v in G.vertex:
        cir = Circle((v.x, v.y), 0.2)
        patches.append(cir)
    # colors = 100 * np.random.rand(len(patches))
    pc = mc.PatchCollection(patches, True)
    # pc.set_array(np.array(colors))

    intersects = []
    for key in G.graph_streets:
        for seg in G.graph_streets[key].segments:
            for item in seg.intersects:
                cir = Circle((item.x, item.y), 0.2, color='red')
                intersects.append(cir)
    pc_intersects = mc.PatchCollection(intersects, match_original=True)
    # pc_intersects.set_color('#FF00FF')


    # lines = [[(2.00, -1.00), (2.00, 2.00), (5.00, 5.00), (5.00, 6.00), (3.00, 8.00)], [(4.00, 2.00), (4.00, 8.00)]]
    lc = mc.LineCollection(lines, colors=c, linewidths=2)
    edge_lc = mc.LineCollection(edges, color=None, linewidths=2)
    fig, (ax1, ax2) = pl.subplots(1,2, sharey=True)
    ax1.add_collection(lc)
    ax2.add_collection(edge_lc)
    ax2.add_collection(pc)
    ax2.add_collection(pc_intersects)
    # ax1.autoscale()
    # ax2.autoscale()
    ax1.margins(0.1)
    ax2.margins(0.1)

    pl.show()
def draw_portrait(input_file, output_file):

    fig, ax = plt.subplots()

    line_expr = re.compile(
        r"""
        ^\(\((?P<r1>\d+),\s(?P<c1>\d+)\) # start of slot (r1, c1)
        ,\s 
        \((?P<r2>\d+),\s(?P<c2>\d+)\)\) # end of slot (r2, c2)
        \s:\s
        \((?P<n>\d),\s(?P<m>\d)\).*$ # tile (n, m)
        """, re.VERBOSE)
    for line in input_file:
        line_match = line_expr.match(line)
        if not line_match:
            continue
        r1 = int(line_match.group('r1'))
        c1 = int(line_match.group('c1'))
        r2 = int(line_match.group('r2'))
        c2 = int(line_match.group('c2'))
        n = int(line_match.group('n'))
        m = int(line_match.group('m'))
        if r1 == r2:
            width = 2
            height = 1
        else:
            width = 1
            height = 2
        if r2 < r1:
            y = 30 - r2
            n, m = m, n
        else:
            y = 30 - r1
        if c2 < c1:
            x = c2
            n, m = m, n
        else:
            x = c1
        rectangles, circles = create_tile((x, y), width, height, (n, m))
        cc = mc.PatchCollection(circles,
                                facecolors='white',
                                edgecolors='white')
        rc = mc.PatchCollection(rectangles,
                                facecolors='black',
                                edgecolors='gray')
        ax.add_collection(rc)
        ax.add_collection(cc)

    ax.set_xlim(0, 22)
    ax.set_ylim(0, 30)
    ax.set_aspect('equal')
    ax.axis('off')

    plt.savefig(output_file, bbox_inches='tight', pad_inches=0)
    plt.show()
def mpl_circle(coords, *colours, **kwargs):
    if 'radius' in kwargs:
        radius = kwargs['radius']
    else:
        radius = 1

    if 'theta0' in kwargs:
        th0 = kwargs['theta0']
    else:
        th0 = 90
    n = len(colours)
    if n == 0:
        raise ValueError("Must specify at least one colour")
    dth = 360 / float(n)
    res = []
    for i in range(n):
        res.append(
            patches.Wedge(coords,
                          radius,
                          th0,
                          th0 + dth,
                          edgecolor='none',
                          facecolor=colours[i]))
        th0 += dth
    return collections.PatchCollection(res, match_original=True)
Example #8
0
def plot_particles_debug(particles, array):

    import matplotlib.pyplot as plt
    import matplotlib.patches as mp
    import matplotlib.collections as mc
    import matplotlib.cm as cm

    fig, axis = plt.subplots()

    patches = []
    colors = []

    for iParticle in range(0, particles.num_particles):
        patches.append(
            mp.Circle((particles.x[iParticle], particles.y[iParticle]),
                      particles.radius[iParticle]))
        colors.append(array[iParticle])

    pc = mc.PatchCollection(patches, cmap=cm.viridis)
    pc.set_array(np.array(colors))

    axis.add_collection(pc)

    fig.colorbar(pc)

    axis.set_xlim((np.amin(np.subtract(particles.x, particles.radius)),
                   np.amax(np.add(particles.x, particles.radius))))
    axis.set_ylim((np.amin(np.subtract(particles.y, particles.radius)),
                   np.amax(np.add(particles.y, particles.radius))))
    axis.set_aspect('equal')

    plt.show()
Example #9
0
def addRingsSlow(centers, innerRadii, outerRadii, **kwargs):
    """Adds a set of rings to an already initialized figure.

    Parameters
    ----------
    centers: object
        Complex numpy array with the circle central coordinates. 
    innerRadii: object
        Numpy array with the ring inner radii. 
    outerRadii: object
        Numpy array with the ring outer radii. 
    kwargs: collections.PatchCollection properties
        Any additional property that should be passed to the patch collection.

    Returns
    -------
    object
        The circles patch collection. 

    """
    # Create the ring collection
    ringList = [
        patches.Wedge((c.real, c.imag), r1, 0, 360, r1 - r2)
        for c, r1, r2 in zip(centers, outerRadii, innerRadii)
    ]
    ringCollection = collections.PatchCollection(ringList, **kwargs)

    # Plot the rings in the current figure
    plt.gca().add_collection(ringCollection)

    return ringCollection
Example #10
0
def GenerateObjectTimeline(file_name, start_times, latencies):
    print("Generating object timeline")
    assert len(start_times) == len(latencies)
    rects = []
    for i, worker_times in enumerate(zip(start_times, latencies)):
        for j, (start_time, latency) in enumerate(np.vstack(worker_times).T):
            rect = mpl_patches.Rectangle((start_time, i + 0.5),
                                         latency,
                                         1.0,
                                         color=(0.5 * (j % 2) + 0.5, 0, 0),
                                         linewidth=0)
            rects.append(rect)
    pc = mplc.PatchCollection(rects, match_original=True)
    fig, ax = plt.subplots(figsize=(30, 5))
    ax.add_collection(pc)
    ax.autoscale()
    ax.margins(0.1)
    print("Saving figure as %s" % file_name)
    plt.savefig(file_name, bbox_inches='tight', dpi=1200)
    print("Figured saved. Rendering figure...")

    selection = DraggableXRange(
        fig, SelectionUpdate(fig, ax, start_times, latencies))
    selection.connect()
    plt.show()
    selection.disconnect()
Example #11
0
def plot_mic_locations(mic_xs, mic_ys):
    fig = plt.gcf()
    ax = fig.gca()
    mic_radius = 1.5

    patches = []
    for coordinate in zip(mic_xs, mic_ys):
        patches.append(mpatches.Circle(coordinate, mic_radius))
    collection = mcollections.PatchCollection(patches,
                                              cmap=cm.brg,
                                              norm=mpl.colors.Normalize(
                                                  0., 1.),
                                              alpha=0.2)
    collection.set_array(np.array([0.25, 0.5, 0.75]))
    ax.add_collection(collection)
    """
    patches = []
    for coordinate in zip(source_xs_120,source_ys_120):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, cmap=cm.brg, norm=mpl.colors.Normalize(0.,1.), alpha=0.2)
    collection.set_array(np.repeat(1.0, len(source_xs_120)))
    ax.add_collection(collection)
    """

    # cavity
    origin_x = np.zeros(1)
    origin_y = np.zeros(1)
    cavity_radius = 10000
    #plt.scatter([0, 0], [0, 0], s=[90000, 0], c=[3,1], cmap=cm.Set1, alpha=0.1)
    cavity = plt.Circle((0, 0), 15.24, color='k', alpha=0.1)
    ax.add_artist(cavity)

    plt.xlim((-16, 16))
    plt.ylim((-16, 16))
Example #12
0
def draw_planogram(boxes, labels, ax=None, xlim=None, ylim=None):
    if ax is None:
        plt.figure(figsize=(12, 9))
        ax = plt.gca()

    if xlim is None:
        xlim = (boxes[:, 0].amin(), boxes[:, 2].amax())
    if ylim is None:
        ylim = (boxes[:, 1].amin(), boxes[:, 3].amax())
    ax.set_xlim(*xlim)
    ax.set_ylim(*ylim)
    ax.set_aspect('equal')
    ax.invert_yaxis()

    box_patches = [
        patches.Rectangle((x1, y1), x2 - x1, y2 - y1)
        for x1, y1, x2, y2 in boxes
    ]
    box_collection = pltcollections.PatchCollection(box_patches,
                                                    facecolor='none',
                                                    edgecolor='black')
    ax.add_collection(box_collection)
    for label, (x1, y1, x2, y2) in zip(labels, boxes):
        x = (x1 + x2) / 2
        y = (y1 + y2) / 2
        ax.text(x, y, label, ha='center', va='center')
Example #13
0
	def plot(self, save_name=None):

		MIN_X, MIN_Y = numpy.amin(self.P, axis=0)
		MAX_X, MAX_Y = numpy.amax(self.P, axis=0)

		MIN_W = numpy.amin(self.W)
		MAX_W = numpy.amax(self.W)
		
		fig, ax = pyplot.subplots()

		circles = [pyplot.Circle((self.P[i][0],self.P[i][1]), radius=self.W[i], linewidth=0) for i in range(self.N)]
		c = collections.PatchCollection(circles)
		ax.add_collection(c)

		for i in range(self.N):
			ax.annotate(self.nodes[i], xy=(self.P[i][0], self.P[i][1]), fontsize=self.W[i]*150/self.N, va="center", ha="center")

		ax.set_xlim(MIN_X - MAX_W, MAX_X + MAX_W)
		ax.set_ylim(MIN_Y - MAX_W, MAX_Y + MAX_W)
		
		ax.set_aspect(1)
		if(save_name):
			pyplot.savefig(self.OUTPUT_FOLDER + save_name)
		else:
			pyplot.show()

		pyplot.clf()
		pyplot.close()
def plot_source_locations(predicted_xs,
                          predicted_ys,
                          actual_xs,
                          actual_ys,
                          error_radius=1.1,
                          cavity_radius=14.22):
    # center marks
    source_xs = np.hstack((predicted_xs, actual_xs))
    source_ys = np.hstack((predicted_ys, actual_ys))

    fig = plt.gcf()
    ax = fig.gca()

    # cavity
    """
    origin_x = np.zeros(1)
    origin_y = np.zeros(1)
    cavity_radius = 14.9 # cm
    cavity=plt.Circle((0,0),cavity_radius,color='k',alpha=0.1)
    ax.add_artist(cavity)
    """

    # error circles
    patches = []
    for coordinate in zip(predicted_xs, predicted_ys):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, color='k', alpha=0.1)
    collection.set_array(np.repeat(0.5, len(predicted_xs)))
    ax.add_collection(collection)

    # 1st Quadrant Microphone
    plt.plot([4.5, 5.5], [6, 6], color='k', linestyle='-', linewidth=2)
    plt.plot([5, 5], [6.5, 5.5], color='k', linestyle='-', linewidth=2)

    # 4th Quadrant Microphone
    plt.plot([4.5, 5.5], [-6, -6], color='k', linestyle='-', linewidth=2)
    plt.plot([5, 5], [-6.5, -5.5], color='k', linestyle='-', linewidth=2)

    # damage marks
    plt.scatter(actual_xs, actual_ys, s=10, c='k', cmap=cm.Set1, alpha=1.0)

    # damage stddev
    damage_stddev = 2.2
    stddev_circle = plt.Circle((1.45392578, -1.7784455),
                               damage_stddev,
                               color='r',
                               alpha=0.1)
    ax.add_artist(stddev_circle)

    mark_radii = np.repeat(10, len(predicted_xs))
    mark_colors = np.repeat(5, len(predicted_xs))
    plt.scatter(predicted_xs,
                predicted_ys,
                s=10,
                c='w',
                cmap=cm.Set1,
                alpha=1.0)

    plt.xlim((-4, 7))
    plt.ylim((-7, 4))
Example #15
0
 def render_matplotlib(self):
     fig = plt.figure(figsize=(10, 6), dpi=80)
     ax = fig.add_subplot(aspect="equal")
     obstacles = self.geoms.geom_objs
     rects = []
     for i, obst in enumerate(obstacles):
         x, y = obst.placement.translation[:2]
         half_side = obst.geometry.halfSide
         w, h = 2 * half_side[:2]
         rects.append(
             patches.Rectangle(
                 (x - w / 2, y - h / 2),
                 w,
                 h  # (x,y)  # width  # height
             ))
     coll = collections.PatchCollection(rects, zorder=1)
     coll.set_alpha(0.6)
     ax.add_collection(coll)
     init = self.state.q
     goal = self.goal_state.q
     ax.set_xlim(0.0, 1.0)
     ax.set_ylim(0.0, 1.0)
     ax.set_xticks([])
     ax.set_yticks([])
     return fig, ax
Example #16
0
def plot_coverage_anisotropy(coverage_map, **kwargs):
    """Plot the coverage anisotropy using 2D glyphs.

    Parameters
    ----------
    kwargs
        Keyword arguments for the Glyphs.

    See also
    --------
    :py:func:`.metrics.coverage_approx`, :py:class:`.Glyph`
    """
    x, y = coverage_map.shape[0:2]
    axis = plt.gca()
    axis.set_aspect('equal')
    plt.xlim([-.5, x - 0.5])
    plt.ylim([-.5, y - 0.5])
    axis.invert_yaxis()
    # Compute coordinates of glyphs
    irange, jrange = np.meshgrid(range(x), range(y))
    irange = irange.flatten()
    jrange = jrange.flatten()
    ij_size = irange.size
    coords = np.stack([irange, jrange], axis=1)
    # Reformat data for glyph making function
    vectors = np.reshape(coverage_map, [ij_size, coverage_map.shape[-1]])
    glyphs = get_pie_glyphs(coords, vectors, snap=False, **kwargs)
    # Add glyphs to axis
    axis.add_collection(
        collections.PatchCollection(glyphs, match_original=True)
    )
Example #17
0
def plot_angle_intensity(angle, intensity, background_color=(0.3, 0.3, 0.3)):
    """Plot the phase angle and intensity in the same plot using 2D glyphs.

    The glyphs are 120 degree pie glyphs whose orientation and hue are
    determined by the angle and whose brightness are determined by the
    intensity.
    """
    assert np.all(angle.shape == intensity.shape)
    x, y = angle.shape[0:2]
    # Compute coordinates of glyphs
    irange, jrange = np.meshgrid(range(x), range(y))
    irange = irange.flatten()
    jrange = jrange.flatten()
    ij_size = irange.size
    coords = np.stack([irange, jrange], axis=1)
    # Generate glyphs
    glyphs = get_angle_intensity_glyphs(coords,
                                        angle.flatten(),
                                        intensity.flatten(),
                                        snap=False)
    # Add glyphs to axis
    axis = plt.gca()
    axis.set_aspect('equal')
    plt.xlim([-.5, x - 0.5])
    plt.ylim([-.5, y - 0.5])
    axis.invert_yaxis()
    axis.set_facecolor(background_color)
    axis.add_collection(
        collections.PatchCollection(glyphs, match_original=True))
Example #18
0
def plot_probe(ax, params, channel_ids=None):

    nb_channels = params.getint('data', 'N_e')

    probe = params.probe
    nodes, edges = get_nodes_and_edges(params)

    positions = []
    for i in list(probe['channel_groups'][1]['geometry'].keys()):
        positions.append(probe['channel_groups'][1]['geometry'][i])
    positions = np.array(positions)
    dx = np.median(np.diff(np.unique(
        positions[:, 0])))  # horizontal inter-electrode distance
    dy = np.median(np.diff(np.unique(
        positions[:, 1])))  # vertical inter-electrode distance

    if channel_ids is None:
        channel_ids = np.arange(0, nb_channels)

    patches = []
    kwargs = dict(
        radius=(min(dx, dy) / 2.0),
        color='tab:gray',
        alpha=0.5,
    )
    for channel_id in channel_ids:
        xy = positions[nodes[channel_id]]
        patch = mpatches.Circle(xy, **kwargs)
        patches.append(patch)
    collection = mcollections.PatchCollection(patches, match_original=True)

    ax.set_aspect('equal')
    ax.add_collection(collection)

    return
    def draw_group(data, panel_params, coord, ax, **params):
        data = coord.transform(data, panel_params)
        fill = to_rgba(data['fill'], data['alpha'])
        color = to_rgba(data['color'], data['alpha'])
        ranges = coord.range(panel_params)

        # For perfect circles the width/height of the circle(ellipse)
        # should factor in the dimensions of axes
        bbox = ax.get_window_extent().transformed(
            ax.figure.dpi_scale_trans.inverted())
        ax_width, ax_height = bbox.width, bbox.height

        factor = ((ax_width / ax_height) * np.ptp(ranges.y) / np.ptp(ranges.x))
        size = data.loc[0, 'binwidth'] * params['dotsize']
        offsets = data['stackpos'] * params['stackratio']

        if params['binaxis'] == 'x':
            width, height = size, size * factor
            xpos, ypos = data['x'], data['y'] + height * offsets
        elif params['binaxis'] == 'y':
            width, height = size / factor, size
            xpos, ypos = data['x'] + width * offsets, data['y']

        circles = []
        for xy in zip(xpos, ypos):
            patch = mpatches.Ellipse(xy, width=width, height=height)
            circles.append(patch)

        coll = mcoll.PatchCollection(circles,
                                     edgecolors=color,
                                     facecolors=fill)
        ax.add_collection(coll)
Example #20
0
def platPrecincts(geoms, mapper):
    axl = plt.axis()

    patchList = []
    for i in range(len(geoms)):
        name = geoms.NAME.iloc[i]
        geom = geoms.geom.iloc[i]

        if geom.IsEmpty():
            continue

        district = mapper.getDistrict(name)[0]
        clr = 'C%i' % (district)

        patches = AnyGeom(geom).as_patch(fc=clr, ec=clr, lw=2, alpha=.2)
        patchList.extend(patches)

    pc = mcollect.PatchCollection(patchList, match_original=True)

    plt.gca().add_collection(pc)
    plt.plot([-76.6, -76.4], [39.2, 39.7], 'w-', zorder=-1)

    #Reset axis
    if axl[0] != 0:
        plt.axis(axl)
    plt.pause(.001)
    def plot(self, grid_dict):
        fig = plt.figure(1, figsize=(10, 10))
        x, y = self.boundary.exterior.xy
        for i in range(len(list(grid_dict.keys()))):
            ax = fig.add_subplot(1, 2, i + 1)
            ax.plot(x, y, color="black")

            patch = []
            occ = []
            key = list(grid_dict.keys())[i]
            for cell in self.cell_list:
                polygon = patches.Polygon(list(cell.exterior.coords), True)
                patch.append(polygon)
                row, col = self.cellToIndex(cell)
                occ.append(grid_dict[key][row][col])

            p = collections.PatchCollection(patch)
            p.set_cmap("Greys")
            p.set_array(np.array(occ))
            ax.add_collection(p)
            fig.colorbar(p, ax=ax)

            ax.set_xlim(
                [self.boundary.bounds[0] - 10, self.boundary.bounds[2] + 10])
            ax.set_ylim(
                [self.boundary.bounds[1] - 10, self.boundary.bounds[3] + 10])

            ax.title.set_text(str(list(grid_dict.keys())[i]))

            # for shark_id, traj in self.timeBinDict[key].items():
            #     ax.plot([mps.x for mps in traj], [mps.y for mps in traj], label=shark_id)

        plt.legend(loc="lower right")
        plt.show()
Example #22
0
 def plot_unit_cells(self,opts='AV',nh=3,nk=4,lvls=10,alpha=0.5,fg='12',**kwargs) :
     '''Display the wallpaper
     pOpt :  A(Atom), V(potential), u(unit_cell), a(asym_unit)
     '''
     fig,ax = dsp.create_fig(figsize=fg,pad=[2.,5]['t' in opts])
     colls,scat,im,cs,lOpt=[],None,None,None,''
     if self.lat_type=='hex' : lOpt += 'hq'
     if 'u' in opts : lattice.plot_lattice(self.lattice_vec,max(nh,3),max(nk,3),pOpt=lOpt,ax=ax)
     if 'a' in opts : colls=[coll.PatchCollection([self.asym_cell],alpha=0.3,linewidth=1.5,edgecolor='b')]
     #plot potential
     if 'V' in opts :
         # na = int(self.Xcell.shape[0]/self.X0.shape[0])
         N = int(np.sqrt(self.Xp.shape[0]))
         (x,y),f = self.Xp.T, self.fp
         # triang = mtri.Triangulation(x, y, Delaunay(self.Xc).vertices)
         # cs=ax.tricontourf(triang,self.fc,levels=lvls)
         # cont = ax.contourf(x.reshape((N,N)),y.reshape((N,N)),f.reshape((N,N)),levels=lvls)
         im = [x.reshape((N,N)),y.reshape((N,N)),f.reshape((N,N))]#,snap=True)
         # cs = ax.pcolormesh(x.reshape((N,N)),y.reshape((N,N)),f.reshape((N,N)))#,snap=True)
     #plot atoms
     if 'A' in opts :
         x,y = self.Xa.T
         s,c = atoms.iloc[self.fa][['size','color']].values.T
         scat=[x.flatten(),y.flatten(),np.int_(50*np.array(s)),c]
     dsp.stddisp(fig=fig,ax=ax,labs=[r'$x(\AA)$',r'$y(\AA)$'],
         scat=scat,colls=colls,im=im+[alpha],contour=im+[lvls],
         title=self.name,name=self.path+self.name,
         **kwargs)
Example #23
0
    def plot(self, ax, **kwargs):
        r"""visualize the spherically symmetric grid in two dimensions

        Args:
            {PLOT_ARGS}
            \**kwargs: Extra arguments are passed on the to the matplotlib
                plotting routines, e.g., to set the color of the lines
        """
        from matplotlib import collections, patches

        kwargs.setdefault("edgecolor", kwargs.get("color", "k"))
        kwargs.setdefault("facecolor", "none")
        (rb, ) = self.axes_bounds
        rmax = rb[1]

        # draw circular parts
        circles = []
        for r in np.linspace(*rb, self.shape[0] + 1):
            if r == 0:
                c = patches.Circle((0, 0), 0.01 * rmax)
            else:
                c = patches.Circle((0, 0), r)
            circles.append(c)
        ax.add_collection(collections.PatchCollection(circles, **kwargs))

        ax.set_xlim(-rmax, rmax)
        ax.set_xlabel("x")
        ax.set_ylim(-rmax, rmax)
        ax.set_ylabel("y")
        ax.set_aspect(1)
Example #24
0
def plot_source_locations(predicted_xs, predicted_ys, actual_xs, actual_ys, error_radius=0.9, cavity_radius=14.22):
    # center marks
    source_xs = np.hstack((predicted_xs, actual_xs))
    source_ys = np.hstack((predicted_ys, actual_ys))

    fig = plt.gcf()
    ax = fig.gca()

    # error circles
    patches = []
    for coordinate in zip(predicted_xs,predicted_ys):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, color='k', alpha=0.1)
    collection.set_array(np.repeat(0.5, len(predicted_xs)))
    ax.add_collection(collection)

    # damage marks
    plt.scatter(actual_xs, actual_ys, s=10, c='k', cmap=cm.Set1, alpha=1.0)

    # damage stddev
    damage_stddev = 2.2
    stddev_circle=plt.Circle((1.45392578, -1.7784455),damage_stddev,color='r',alpha=0.1)
    ax.add_artist(stddev_circle)

    mark_radii = np.repeat(10, len(predicted_xs))
    mark_colors = np.repeat(5, len(predicted_xs))
    plt.scatter(predicted_xs, predicted_ys, s=10, c='w', cmap=cm.Set1, alpha=1.0)

    plt.xlim((-4, 7))
    plt.ylim((-7, 4))
Example #25
0
def addThickLines(startPoints, endPoints, thicknesses, **kwargs):
    """Adds a set of thick lines to an already initialized figure.

    Parameters
    ----------
    startPoints: object
        Complex numpy array with the lines start coordinates. 
    endPoints: object
        Complex numpy array with the lines end coordinates. 
    thicknesses: object
        Numpy array with the lines thicknesses.
    kwargs: collections.LineCollection properties
        Any additional property that should be passed to the line collection.

    Returns
    -------
    object
        The thick lines patch collection.
         
    """
    # Create the thick line collection
    centers = (endPoints + startPoints) / 2
    difference = endPoints - startPoints
    widths = np.abs(difference)
    angles = np.angle(difference)
    thickLineList = [
        getThickLinePath(c, w, t, a)
        for c, w, t, a in zip(centers, widths, thicknesses, angles)
    ]
    thickLineCollection = collections.PatchCollection(thickLineList, **kwargs)

    # Plot the thick lines in the current figure
    plt.gca().add_collection(thickLineCollection)

    return thickLineCollection
Example #26
0
def plot_capacity_thumbs(figure, thumbs, year):
    (fig, ax) = figure
    cap_thumbs = []
    thumb_colors = []
    for thumb in thumbs:
        maxcap = thumbs[thumb].capacities[str(year)]
        supply = thumbs[thumb].supplies[str(year)]
        (x, y) = thumbs[thumb].coordinates
        maxcap_rect = Rectangle((int(x), int(y)), 7000, supply)
        thumb_colors.append('grey')
        #supply_rect1 = Rectangle((int(x+7000), int(y)), 7000, maxcap-supply)
        #thumb_colors.append('white')
        cap_thumbs.append(maxcap_rect)
        if maxcap > supply:
            supply_rect2 = Rectangle((int(x), int(y) + supply), 7000,
                                     maxcap - supply)
            thumb_colors.append('white')
            #cap_thumbs.append(supply_rect1) # unused capacity next to used
            cap_thumbs.append(supply_rect2)  # unused capacity on top of used
    q = mplc.PatchCollection(cap_thumbs,
                             linewidth=1,
                             facecolors=thumb_colors,
                             alpha=0.5,
                             edgecolor='grey',
                             zorder=3)
    ax.add_collection(q)
    return (fig, ax)
Example #27
0
def visualizeHaarFeatures():
    fig = figure()
    ax = fig.add_subplot(111)
    ax.set_xlim([0, 1])  # pylab.xlim([-400, 400])
    ax.set_ylim([0, 1])  # pylab.ylim([-400, 400])
    patches = []

    cc = ColorConverter()
    outer = cc.to_rgba("#BFCBDE", alpha=0.5)
    inner = cc.to_rgba("RED", alpha=0.5)

    for row in generateHaarFeatures(100):
        #print row
        patches.append(gca().add_patch(
            Rectangle((row[0], row[1]),
                      row[2] - row[0],
                      row[3] - row[1],
                      color=outer)))
        patches.append(gca().add_patch(
            Rectangle((row[4], row[5]),
                      row[6] - row[4],
                      row[7] - row[5],
                      color=inner)))
    p = collections.PatchCollection(patches)

    patches = ax.add_collection(p)

    show()
Example #28
0
    def cone(self,
             plunge,
             bearing,
             angle,
             segments=100,
             bidirectional=True,
             **kwargs):
        """
        Plot a polygon of a small circle (a.k.a. a cone) with an angular radius
        of *angle* centered at a p/b of *plunge*, *bearing*. Additional keyword
        arguments are passed on to the ``PathCollection``.  (e.g. to have an
        unfilled small small circle, pass "facecolor='none'".)

        Parameters
        ----------
        plunge : number or sequence of numbers
            The plunge of the center of the cone in degrees.
        bearing : number or sequence of numbers
            The bearing of the center of the cone in degrees.
        angle : number or sequence of numbers
            The angular radius of the cone in degrees.
        segments : int, optional
            The number of vertices to use for the cone. Defaults to 100.
        bidirectional : boolean, optional
            Whether or not to draw two patches (the one given and its antipode)
            for each measurement. Defaults to True.
        **kwargs
            Additional parameters are ``matplotlib.collections.PatchCollection``
            properties.

        Returns
        -------
        collection : ``matplotlib.collections.PathCollection``

        Notes
        -----
        If *bidirectional* is ``True``, two circles will be plotted, even if
        only one of each pair is visible. This is the default behavior.
        """
        plunge, bearing, angle = np.atleast_1d(plunge, bearing, angle)
        patches = []
        lons, lats = stereonet_math.cone(plunge, bearing, angle, segments)
        codes = mpath.Path.LINETO * np.ones(segments, dtype=np.uint8)
        codes[0] = mpath.Path.MOVETO

        if bidirectional:
            p, b = -plunge, bearing + 180
            alons, alats = stereonet_math.cone(p, b, angle, segments)
            codes = np.hstack([codes, codes])
            lons = np.hstack([lons, alons])
            lats = np.hstack([lats, alats])

        for lon, lat in zip(lons, lats):
            xy = np.vstack([lon, lat]).T
            path = mpath.Path(xy, codes)
            patches.append(mpatches.PathPatch(path))

        col = mcollections.PatchCollection(patches, **kwargs)
        self.add_collection(col)
        return col
    def run_simulation(self):
        self.plot_network()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        for step in range(self.nsteps):
            ax.clear()
            actives = np.empty((sum(self.layer_nodes)))
            start = 0
            for layer_ind in range(self.layers):
                actives[start:start + self.
                        layer_nodes[layer_ind]] = self.data[layer_ind][:, step]
                start += self.layer_nodes[layer_ind]
            active_indices = np.where(actives == 1)[0]  #nodes that are spiked
            inactive_indices = np.where(actives == 0)[0]
            for ind in active_indices:
                self.patches[ind].set_color('red')
            for ind in inactive_indices:
                self.patches[ind].set_color('black')

            patches_collection = collections.PatchCollection(
                self.patches, match_original=True)
            ax.add_collection(patches_collection)
            plt.draw()
            plt.axis('scaled')
            plt.axis('off')
            plt.pause(0.1)
def plot_source_locations(predicted_xs,
                          predicted_ys,
                          actual_xs,
                          actual_ys,
                          error_radius=0.9,
                          cavity_radius=14.22):
    # center marks
    #source_xs = np.hstack((predicted_xs, actual_xs))
    #source_ys = np.hstack((predicted_ys, actual_ys))

    mark_radii = np.repeat(10, len(predicted_xs))
    mark_colors = np.repeat(5, len(predicted_xs))
    plt.scatter(predicted_xs,
                predicted_ys,
                s=10,
                c='k',
                cmap=cm.Set1,
                alpha=1.0)

    fig = plt.gcf()
    ax = fig.gca()

    # error circles
    """
    patches = []
    for coordinate in zip(predicted_xs,predicted_ys):
        patches.append(mpatches.Circle(coordinate, error_radius))
    collection = mcollections.PatchCollection(patches, color='k', alpha=0.2)
    collection.set_array(np.repeat(0.5, len(predicted_xs)))
    ax.add_collection(collection)
    """

    # damage marks
    patches = []
    for coordinate in zip(actual_xs, actual_ys):
        patches.append(mpatches.RegularPolygon(coordinate, 5, 0.4))
    collection = mcollections.PatchCollection(patches, color='k', alpha=0.2)
    #collection.set_array(np.repeat(0.5, len(source_xs_0)))
    ax.add_collection(collection)

    # Residual Lines
    for coordinate in zip(actual_xs, actual_ys, predicted_xs, predicted_ys):
        plt.plot([coordinate[0], coordinate[2]],
                 [coordinate[1], coordinate[3]],
                 color='k',
                 linestyle='-',
                 linewidth=2)

    good_radius = 6.0  # cm
    good_ragion = plt.Circle((0, 0), good_radius, color='k', fill=False)
    ax.add_artist(good_ragion)

    # cavity
    cavity_radius = 14.13  # cm
    cavity = plt.Circle((0, 0), cavity_radius, color='k', alpha=0.1)
    ax.add_artist(cavity)

    plt.xlim((-16, 16))
    plt.ylim((-16, 16))