Пример #1
0
 def _create_square_patches(pix_x, pix_y, pix_width, pix_rotation):
     orientation = (pix_rotation + 45 * u.deg).to_value(u.rad)
     return [
         RegularPolygon(
             (x, y),
             4,
             # convert from edge length to outer circle radius
             radius=w / np.sqrt(2),
             orientation=orientation,
             fill=True,
         ) for x, y, w in zip(pix_x, pix_y, pix_width)
     ]
Пример #2
0
 def _create_hex_patches(pix_x, pix_y, pix_width, pix_rotation):
     orientation = pix_rotation.to_value(u.rad)
     return [
         RegularPolygon(
             (x, y),
             6,
             # convert from incircle to outer circle radius
             radius=w / np.sqrt(3),
             orientation=orientation,
             fill=True,
         ) for x, y, w in zip(pix_x, pix_y, pix_width)
     ]
Пример #3
0
 def __init__(self):
     self.contorno = RegularPolygon((0, 0),
                                    numVertices=4,
                                    radius=np.sqrt(50**2 + 50**2),
                                    orientation=np.radians(45),
                                    facecolor="blue",
                                    alpha=0.1,
                                    edgecolor='k')
     self.ax.add_patch(self.contorno)  # se dibuja el contorno
     self.ax.scatter(
         0, 0, c='k', alpha=0.5, marker='1'
     )  # Se dibuja un punto negro representando a la estación base
Пример #4
0
def _draw_coords_axial_format(hexes, ax):
    for h in hexes:
        x, y = cc.planer_position(h.cube_coords)
        patch = RegularPolygon((x, y), numVertices=6, facecolor="white", radius=2 / 3, orientation=0, edgecolor="k")
        ax.add_patch(patch)

        q, r = cc.cube_to_axial(h.cube_coords)
        q, r = int(q), int(r)
        if (q, r) == (0, 0):
            q, r = "q", "r"
        ax.text(x - 1 / 3 + 0.05, y, q, color="dodgerblue", ha="center", va="center", size=18)
        ax.text(x + 1 / 3 - 0.05, y, r, color="limegreen", ha="center", va="center", size=18)
Пример #5
0
 def _gen_axes_patch(self):
     # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
     # in axes coordinates.
     if frame == 'circle':
         return Circle((0.5, 0.5), 0.5)
     elif frame == 'polygon':
         return RegularPolygon((0.5, 0.5),
                               num_vars,
                               radius=.5,
                               edgecolor="k")
     else:
         raise ValueError("unknown value for 'frame': %s" % frame)
Пример #6
0
    def draw(self):
        super().draw()

        # draw the arrow
        center, direction = self.arrow_specs()
        self.arrow = RegularPolygon(center,
                                    3,
                                    color='orange',
                                    radius=0.4,
                                    direction=direction)
        ax = plt.gca()
        ax.add_patch(self.arrow)
Пример #7
0
def plot_plate(data, edge_color='#888888', output_filename=None):
    """Plot of the plate color mapping.

	The function will plot the color mapping in `data`:
	a grid with enough columns and rows for the ``Col`` and ``Row`` columns in `data`,
	where the color of each grid cell given by the ``Color`` column.

	Parameters
	----------
	data : pandas.DataFrame
		growth curve data, see :py:mod:`curveball.ioutils` for a detailed definition.
	edge_color : str
		color hex string for the grid edges.

	Returns
	-------
	fig : matplotlib.figure.Figure
		figure object
	ax : numpy.ndarray
		array of axis objects.
	"""
    plate = data.pivot('Row', 'Col', 'Color').as_matrix()
    height, width = plate.shape
    fig = plt.figure(figsize=((width + 2.0) / 3.0, (height + 2.0) / 3.0))
    ax = fig.add_axes((0.05, 0.05, 0.9, 0.9),
                      aspect='equal',
                      frameon=False,
                      xlim=(-0.05, width + 0.05),
                      ylim=(-0.05, height + 0.05))
    for axis in (ax.xaxis, ax.yaxis):
        axis.set_major_formatter(plt.NullFormatter())
        axis.set_major_locator(plt.NullLocator())

    # Create the grid of squares
    squares = np.array([[
        RegularPolygon((i + 0.5, j + 0.5),
                       numVertices=4,
                       radius=0.5 * np.sqrt(2),
                       orientation=old_div(np.pi, 4),
                       ec=edge_color,
                       fc=plate[height - 1 - j, i]) for j in range(height)
    ] for i in range(width)])
    [ax.add_patch(sq) for sq in squares.flat]
    ax.set_xticks(np.arange(width) + 0.5)
    ax.set_xticklabels(np.arange(1, 1 + width))
    ax.set_yticks(np.arange(height) + 0.5)
    ax.set_yticklabels(ascii_uppercase[height - 1::-1])
    ax.xaxis.tick_top()
    ax.yaxis.tick_left()
    ax.tick_params(length=0, width=0)
    if output_filename:
        fig.savefig(output_filename, bbox_inches='tight', pad_inches=1)
    return fig, ax
Пример #8
0
 def _gen_axes_patch(self):
     # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
     # in axes coordinates.
     if frame == 'Circle':
         from matplotlib.patches import Circle
         return Circle((0.5, 0.5), 0.5)
     elif frame == 'polygon':
         from matplotlib.patches import RegularPolygon
         return RegularPolygon((0.5, 0.5),
                               nvars,
                               radius=.5,
                               edgecolor="k")
 def plotHexMap(f, Col, X, Y, n, rad=0.012):
     for i in range(n):
         hex = RegularPolygon((X[i], Y[i]),
                              numVertices=6,
                              radius=rad,
                              facecolor=Col[i],
                              edgecolor='none')
         f.add_patch(hex)
         f.axis(np.array([-1, 1, -1, 1]) * 0.9)
         f.set_aspect(np.diff(f.get_xlim()) / np.diff(f.get_ylim()))
         f.set_xticks([])
         f.set_yticks([])
Пример #10
0
def plot_map(grid, d_matrix):
    """
    Plot hexagon map where each neuron is represented by a hexagon.
    """
    n_centers = grid['centers']
    r = grid['r']
    ax = plt.gca()
    ax.axis('equal')
    # Discover difference between centers
    for xy in n_centers:
        patch = RegularPolygon(xy,
                               numVertices=6,
                               radius=r,
                               color='none',
                               ec='k')
        ax.add_patch(patch)
        patch.set_transform(ax.transData)
    ax.autoscale_view()
    plt.axis('off')

    return ax
    def __init__(self, dim=15, num_mines=45, fog_probability=0.2):
        self.dim = dim
        self.num_mines = num_mines 
        
        # fog probability is the chance that the board will not return the hint 
        #  to the agent.  It will instead return a integer value of -2, signifying that 
        #  a hint was not provided.  
        self.fog_probability = fog_probability

        # grid of cells of the board.  Shows mines (-1) and minecounts  
        self.cells = np.zeros((dim, dim))
        
        # grid of bools.  True if agent has excavated the cell at i, j 
        self.excavated = np.zeros((dim, dim), dtype=bool) 
        
        # grid of bools.  True if agent has placed a flag at i, j
        self.flags = np.zeros((dim, dim), dtype=object)


        # Boolean marking if game is complete 
        self.gameover = False 
        # Score value will be populated to this attribute upon gameover 
        self.score = None 
        
        # Create the figure and axes 
        self.fig = plt.figure(figsize=((dim + 2) / 3., (dim + 2) / 3.))
        self.ax = self.fig.add_axes((0.05, 0.05, 0.9, 0.9),
                                    aspect='equal', frameon=False,
                                    xlim=(-0.05, dim + 0.05),
                                    ylim=(-0.05, dim + 0.05))
        for axis in (self.ax.xaxis, self.ax.yaxis):
            axis.set_major_formatter(plt.NullFormatter())
            axis.set_major_locator(plt.NullLocator())


        # Create the grid of squares
        self.squares = np.array([[RegularPolygon((i + 0.5, j + 0.5),
                                                 numVertices=4,
                                                 radius=0.5 * np.sqrt(2),
                                                 orientation=np.pi / 4,
                                                 ec='black',
                                                 fc='lightgray')
                                  for j in range(dim)]
                                 for i in range(dim)])
        [self.ax.add_patch(sq) for sq in self.squares.flat]
        
        
        self.place_mines() 
        self.assign_mine_counts()
        
        # Event hook for mouse clicks
        self.fig.canvas.mpl_connect('button_press_event', self._button_press)       
Пример #12
0
class ClipWindow:
    def __init__(self, ax, line):
        self.ax = ax
        ax.set_title('drag polygon around to test clipping')
        self.canvas = ax.figure.canvas
        self.line = line
        self.poly = RegularPolygon(
            (200, 200), numVertices=10, radius=100,
            facecolor='yellow', alpha=0.25,
            transform=transforms.IdentityTransform())

        ax.add_patch(self.poly)
        self.canvas.mpl_connect('button_press_event', self.onpress)
        self.canvas.mpl_connect('button_release_event', self.onrelease)
        self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.x, self.y = None, None

    def onpress(self, event):
        self.x, self.y = event.x, event.y

    def onrelease(self, event):
        self.x, self.y = None, None

    def onmove(self, event):

        if self.x is None: return
        dx = event.x - self.x
        dy = event.y - self.y
        self.x, self.y = event.x, event.y
        x, y = self.poly.xy
        x += dx
        y += dy
        #print self.y, event.y, dy, y
        self.poly.xy = x,y
        self._clip()

    def _clip(self):
        self.line.set_clip_path(self.poly.get_path(), self.poly.get_transform())
        self.canvas.draw_idle()
Пример #13
0
def _draw_coords_cube_format(hexes, ax):
    for h in hexes:
        x, y = cc.planer_position(h.cube_coords)
        patch = RegularPolygon((x, y), numVertices=6, facecolor="white", radius=2 / 3, orientation=0, edgecolor="k")
        ax.add_patch(patch)

        q, r, s = h.cube_coords
        q, r, s = int(q), int(r), int(s)
        if (q, r, s) == (0, 0, 0):
            q, r, s, = "x", "z", "y"
        ax.text(x - 1 / 3 + 0.05, y + 2 / 9 - 0.04, q, color="red", ha="center", va="center", size=16)
        ax.text(x + 1 / 3 - 0.05, y + 2 / 9 - 0.04, r, color="blue", ha="center", va="center", size=16)
        ax.text(x, y - 4 / 9 + 0.12, s, color="green", ha="center", va="center", size=16)
Пример #14
0
def valve_patches(coords, size, **kwargs):
    polys, lines = list(), list()
    facecolor = kwargs.pop('patch_facecolor')
    colors = get_color_list(facecolor, len(coords))
    lw = kwargs.get("linewidths", 2.)
    filled = kwargs.pop("filled", np.full(len(coords), 0, dtype=np.bool))
    filled = get_filled_list(filled, len(coords))
    for geodata, col, filled_ind in zip(coords, colors, filled):
        p1, p2 = np.array(geodata[0]), np.array(geodata[-1])
        diff = p2 - p1
        angle = np.arctan2(*diff)
        vec_size = _rotate_dim2(np.array([0, size]), angle)
        centroid_tri1 = p1 + diff / 2 - vec_size
        centroid_tri2 = p1 + diff / 2 + vec_size
        face_col = "w" if not filled_ind else col
        polys.append(RegularPolygon(centroid_tri1, numVertices=3, radius=size, orientation=-angle,
                                    ec=col, fc=face_col, lw=lw))
        polys.append(RegularPolygon(centroid_tri2, numVertices=3, radius=size,
                                    orientation=-angle+np.pi/3, ec=col, fc=face_col, lw=lw))
        lines.append([p1, p1 + diff / 2 - vec_size / 2 * 3])
        lines.append([p2, p1 + diff / 2 + vec_size / 2 * 3])
    return lines, polys, {"filled"}
Пример #15
0
def polygon_patches(node_coords, radius, num_edges, color=None, **kwargs):
    """
    Function to create a list of polygon patches from node coordinates. The number of edges for the
    polygon can be defined.

    :param node_coords: coordinates of the nodes to draw
    :type node_coords: iterable
    :param radius: radius for the polygon (from centroid to edges)
    :type radius: float
    :param num_edges: number of edges of the polygon
    :type num_edges: int
    :param color: color or colors of the patches
    :type color: iterable, float
    :param kwargs: additional keyword arguments to pass to the Polygon initialization
    :type kwargs: dict
    :return: patches - list of rectangle patches for the nodes
    """
    if not MATPLOTLIB_INSTALLED:
        soft_dependency_error(
            str(sys._getframe().f_code.co_name) + "()", "matplotlib")
    patches = list()
    if color is not None:
        colors = get_color_list(color, len(node_coords))
        for (x, y), col in zip(node_coords, colors):
            patches.append(
                RegularPolygon([x, y],
                               numVertices=num_edges,
                               radius=radius,
                               color=color,
                               **kwargs))
    else:
        for x, y in node_coords:
            patches.append(
                RegularPolygon([x, y],
                               numVertices=num_edges,
                               radius=radius,
                               **kwargs))
    return patches
Пример #16
0
def _draw_hexes(hexes, ax):
    for h in hexes:
        x, y = cc.planer_position(h.cube_coords)
        colour = facts.RESOURCE_COLOURS[h.resource]
        label = h.value
        label_colour = value_colours(h.value)

        patch = RegularPolygon((x, y), numVertices=6, facecolor=colour, radius=2 / 3, orientation=0, edgecolor="k")
        ax.add_patch(patch)
        if ":" in str(label):
            size = 8 if "2:1" in label else 15
        else:
            size = 20
        ax.text(x, y, label, color=label_colour, ha="center", va="center", size=size)
Пример #17
0
 def render(self, mode='human'):
     self.ax = self.fig.get_axes()[0]
     self.ax.cla()
     patch_list = []
     patch_list += self.fixed_patches
     tpat = RegularPolygon(xy=(self.target_coord_cartesian[0],
                               self.target_coord_cartesian[1]),
                           numVertices=6,
                           radius=.04,
                           fc='darkorange')  # target
     patch_list.append(tpat)
     cpat = Circle(xy=(self.catcher_coord_cartesian[0],
                       self.catcher_coord_cartesian[1]),
                   radius=.03,
                   fc='black')  # catcher
     patch_list.append(cpat)
     pc = PatchCollection(
         patch_list, match_original=True
     )  # match_origin prevent PatchCollection mess up original color
     # plot patches
     self.ax.add_collection(pc)
     # plot cables
     self.ax.plot(
         [self.catcher_coord_cartesian[0], self.puller_locations[0, 0]],
         [self.catcher_coord_cartesian[1], self.puller_locations[0, 1]],
         linewidth=.1,
         color='k')
     self.ax.plot(
         [self.catcher_coord_cartesian[0], self.puller_locations[1, 0]],
         [self.catcher_coord_cartesian[1], self.puller_locations[1, 1]],
         linewidth=.1,
         color='k')
     self.ax.plot(
         [self.catcher_coord_cartesian[0], self.puller_locations[2, 0]],
         [self.catcher_coord_cartesian[1], self.puller_locations[2, 1]],
         linewidth=.1,
         color='k')
     # plot catcher's trajectory
     if self.traj_catcher:
         traj_c = np.array(self.traj_catcher)
         self.ax.plot(traj_c[-100:, 0],
                      traj_c[-100:, 1],
                      linestyle=':',
                      linewidth=0.5,
                      color='black')
     # Set ax
     self.ax.axis(np.array([-1.2, 1.2, -1., 1.4]))
     self.ax.grid(color='grey', linestyle=':', linewidth=0.5)
     plt.pause(0.02)
     self.fig.show()
Пример #18
0
def create_load_collection(net,
                           loads=None,
                           size=1.,
                           infofunc=None,
                           orientation=np.pi,
                           **kwargs):
    load_table = net.load if loads is None else net.load.loc[loads]
    """
    Creates a matplotlib patch collection of pandapower loads.

    Input:
        **net** (pandapowerNet) - The pandapower network

    OPTIONAL:
        **size** (float, 1) - patch size

        **infofunc** (function, None) - infofunction for the patch element

        **orientation** (float, np.pi) - orientation of load collection. pi is directed downwards,
            increasing values lead to clockwise direction changes.

        **kwargs - key word arguments are passed to the patch function

    OUTPUT:
        **load1** - patch collection

        **load2** - patch collection
    """
    lines = []
    polys = []
    infos = []
    off = 2.
    ang = orientation if hasattr(
        orientation, '__iter__') else [orientation] * net.load.shape[0]
    color = kwargs.pop("color", "k")
    for i, load in load_table.iterrows():
        p1 = net.bus_geodata[["x", "y"]].loc[load.bus]
        p2 = p1 + _rotate_dim2(np.array([0, size * off]), ang[i])
        p3 = p1 + _rotate_dim2(np.array([0, size * (off - 0.5)]), ang[i])
        polys.append(
            RegularPolygon(p2, numVertices=3, radius=size,
                           orientation=-ang[i]))
        lines.append((p1, p3))
        if infofunc is not None:
            infos.append(infofunc(i))
    load1 = PatchCollection(polys, facecolor="w", edgecolor=color, **kwargs)
    load2 = LineCollection(lines, color=color, **kwargs)
    load1.info = infos
    load2.info = infos
    return load1, load2
Пример #19
0
class ClipWindow:
    def __init__(self, ax, line):
        self.ax = ax
        ax.set_title('drag polygon around to test clipping')
        self.canvas = ax.figure.canvas
        self.line = line
        self.poly = RegularPolygon(
            (200, 200), numVertices=10, radius=100,
            facecolor='yellow', alpha=0.25,
            transform=transforms.identity_transform())

        ax.add_patch(self.poly)
        self.canvas.mpl_connect('button_press_event', self.onpress)
        self.canvas.mpl_connect('button_release_event', self.onrelease)
        self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.x, self.y = None, None


    def onpress(self, event):
        self.x, self.y = event.x, event.y

    def onrelease(self, event):
        self.x, self.y = None, None

    def onmove(self, event):

        if self.x is None: return
        dx = event.x - self.x
        dy = event.y - self.y
        self.x, self.y = event.x, event.y
        x, y = self.poly.xy
        x += dx
        y += dy
        #print self.y, event.y, dy, y
        self.poly.xy = x,y
        self._clip()

    def _clip(self):
        fig = self.ax.figure
        l,b,w,h = fig.bbox.get_bounds()
        path = agg.path_storage()

        for i, xy in enumerate(self.poly.get_verts()):
            x,y = xy
            y = h-y
            if i==0: path.move_to(x,y)
            else:    path.line_to(x,y)
        path.close_polygon()
        self.line.set_clip_path(path)
        self.canvas.draw_idle()
    def draw_token(cls, token, r, c, ax, height, width, token_scale=1.0):
        if token == EMPTY:
            edge_color = '#888888'
            face_color = 'white'

            drawing = RegularPolygon((c + 0.5, (height - 1 - r) + 0.5),
                                     numVertices=4,
                                     radius=0.5 * np.sqrt(2),
                                     orientation=np.pi / 4,
                                     ec=edge_color,
                                     fc=face_color)
            ax.add_patch(drawing)

            return drawing

        else:
            edge_color = '#888888'
            face_color = '#DDDDDD'

            drawing = RegularPolygon((c + 0.5, (height - 1 - r) + 0.5),
                                     numVertices=4,
                                     radius=0.5 * np.sqrt(2),
                                     orientation=np.pi / 4,
                                     ec=edge_color,
                                     fc=face_color)
            ax.add_patch(drawing)

            im = TOKEN_IMAGES[token]
            oi = OffsetImage(im,
                             zoom=cls.fig_scale *
                             (token_scale / max(height, width)**0.5))
            box = AnnotationBbox(oi, (c + 0.5, (height - 1 - r) + 0.5),
                                 frameon=False)

            ax.add_artist(box)

            return box
Пример #21
0
def main():
    # Creating arrays for domain and displacement
    dx = 20e-6
    dy = 20e-6
    x = np.arange(-10e-3, 10e-3, dx)
    y = np.arange(-10e-3, 10e-3, dy)

    # Wavespeed - define a hexagon
    c = np.ones([len(x), len(y)]) * 10
    radius = 10e-3

    mask = hexagon_mask(x, y, radius)
    c[mask] = 3000

    A = np.zeros(c.shape)
    A[499:501, 499:501] = 1

    # Add hexagon on plot to delineate the domain
    hexagon = RegularPolygon((0, 0),
                             numVertices=6,
                             radius=1e3 * radius,
                             alpha=.5)

    # Create wavesolver instance
    Soln = WaveSolver(x, y, c, dt=2.5e-9, params=(A, 2e6, 4e-7, 0e-3))

    # Get first timestep to set up plot
    u = Soln.get_snapshot()

    # Create image plot
    Extent = (1e3 * x.min(), 1e3 * x.max(), 1e3 * y.min(), 1e3 * y.max())
    fig, ax = plt.subplots()
    ax.add_patch(hexagon)
    im = ax.imshow(u.T,
                   aspect='auto',
                   origin='lower',
                   extent=Extent,
                   clip_path=hexagon,
                   clip_on=True)

    init(fig, ax, im)

    # Animate through
    anim = FuncAnimation(fig,
                         animate,
                         fargs=(im, ax, Soln),
                         frames=np.arange(0, 20.e-6, 0.05e-6),
                         repeat=False)
    return anim
def update(val):
    curtime = sTime.val
    [p.remove() for p in reversed(ax.patches)]
    ncar_per_Bs = BS_get_Ncar_by_time(traces, curtime)
    for x, y, ncar in zip(bs_coordinates['x'], bs_coordinates['y'],
                          ncar_per_Bs):
        curr_color = cmap(ncar / auto_per_BS)
        hex = RegularPolygon((x, y),
                             numVertices=6,
                             radius=40,
                             orientation=np.radians(30),
                             facecolor=curr_color,
                             edgecolor='k')
        ax.add_patch(hex)
    fig.canvas.draw_idle()
Пример #23
0
    def grid(self):
        """Constructs and returns the grid for this plot

        Returns:
            PatchCollection containg the grid
        """
        grid = [
            RegularPolygon((self.radius, self.radius), self.num_vertices,
                           self.radius)
        ]
        num_ticks = int(self.maxval) / self.interval
        for i in xrange(num_ticks):
            val = float(i) / num_ticks * self.radius
            grid.append(
                RegularPolygon((self.radius, self.radius), self.num_vertices,
                               val))
        facecolors = [(1, 1, 1, 0)] * len(grid)
        edgecolors = ['k'] + [(0, 0, 0, 0.4)] * len(grid[1:])
        linewidths = [0.5] + [0.2] * len(grid[1:])
        return PatchCollection(grid,
                               facecolors=facecolors,
                               edgecolors=edgecolors,
                               linewidths=linewidths,
                               zorder=1)
Пример #24
0
    def __init__(self, ax, line):
        self.ax = ax
        ax.set_title('drag polygon around to test clipping')
        self.canvas = ax.figure.canvas
        self.line = line
        self.poly = RegularPolygon(
            (200, 200), numVertices=10, radius=100,
            facecolor='yellow', alpha=0.25,
            transform=transforms.IdentityTransform())

        ax.add_patch(self.poly)
        self.canvas.mpl_connect('button_press_event', self.onpress)
        self.canvas.mpl_connect('button_release_event', self.onrelease)
        self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.x, self.y = None, None
Пример #25
0
    def get_nodes_within_hexagon(self, center, radius, stream_id):
        """
        Get nodes inside a hexagon

        :param center: x+yj
        :param radius: float
        :param stream_id: str
        :return: array of ints (neuron indices)
        """

        output_grid = self.corem_positions[stream_id]

        hexagon = RegularPolygon((center.real, center.imag), 6, radius=radius)
        hexagon_path = hexagon.get_path(
        )  # matplotlib returns the unit hexagon
        hexagon_tf = hexagon.get_transform(
        )  # which can then be transformed to give the real path
        real_hexagon_path = hexagon_tf.transform_path(hexagon_path)

        output_grid_tuples = [(z.real, z.imag) for z in output_grid]
        wanted_indices = np.where(
            real_hexagon_path.contains_points(output_grid_tuples))

        return wanted_indices[0]
Пример #26
0
def update_bs_cells(traces, curtime, figurename, bs_position,
                    cmap_scale_color):
    [old_patches.remove() for old_patches in reversed(figurename.patches)]
    cars_per_bs = vf.BS_get_Ncar_by_time(traces, curtime)
    for xbs, ybs, ncarbs in zip(bs_position['x'], bs_position['y'],
                                cars_per_bs):
        color = cmap_scale_color(ncarbs / auto_per_BS)
        hex_patch_apply = RegularPolygon((xbs, ybs),
                                         numVertices=6,
                                         radius=40,
                                         orientation=np.radians(30),
                                         facecolor=color,
                                         edgecolor='k')
        figurename.add_patch(hex_patch_apply)
    fig.canvas.draw_idle()
Пример #27
0
    def show_floor(self, scale=0.15, floor=None):
        colors = {1: "green", 0: "blue"}
        if not floor:
            tiles = self.tiles
            active = self.active
        else:
            tiles, active = floor
        m = scale * np.sin(np.radians(60))
        coord = lambda x, y, z: (scale * (x - y) / 2, -m * z)

        fig, ax = plt.subplots(1)
        fig.set_dpi(250)
        ax.set_aspect('equal')
        ax.axis('off')

        def get_color(loc):
            if loc == (0, 0, 0): return 'red'
            return colors[tiles[loc] % 2]

        # Add some coloured hexagons
        xlim = -1, 1
        ylim = -1, 1
        for location, state in tiles.items():
            x, y = coord(*location)
            xlim = min(x, xlim[0]), max(x, xlim[1])
            ylim = min(y, ylim[0]), max(y, ylim[1])
            hex = RegularPolygon((x, y),
                                 numVertices=6,
                                 radius=scale / np.sqrt(3),
                                 orientation=np.radians(60),
                                 facecolor=get_color(location),
                                 alpha=1,
                                 edgecolor='k')
            ax.add_patch(hex)
            ax.text(x,
                    y + scale * 0.2,
                    str(active[location]),
                    ha='center',
                    va='center',
                    size=4)
            ax.text(x,
                    y - scale * 0.1,
                    str(location),
                    ha='center',
                    va='center',
                    size=3)
        ax.set(xlim=xlim, ylim=ylim)
        return ax
Пример #28
0
def plotear_grid(coef, radio, coord, nivel):
    '''Plotea graficas de celdas hexagonales'''
    # Horizontal cartesian coords
    ##hcoord = [coef*c[0] for c in coord]

    labels = crear_labels(coord)
    colors = crear_color(coord)
    ##print("labels: ",labels )
    # Vertical cartersian coords
    #calcula el centro de los hexagonos
    hcoord, vcoord = crear_coordenadas_grilla_horizontal(coord, coef, nivel)

    ####cordenada x pares arriba, impares abajo
    ##vcoord = [-1*2. * np.sin(np.radians(60)) * (coef*c[1] - coef*c[2]) /3. for c in coord]

    ##print("coordenadas vcord", vcoord )

    #el numero de colores debe ser igual a len(coord)

    fig, ax = plt.subplots(1)
    ax.set_aspect('equal')
    vertical_coef = 1.154
    vertical_coef = 1

    print(len(hcoord), len(vcoord))

    for x, y, c, l in zip(hcoord, vcoord, colors, labels):
        color = c[0].lower(
        )  # matplotlib understands lower case words for colours
        hex = RegularPolygon(
            (x, y),
            numVertices=6,
            radius=vertical_coef * radio,  #0.67
            orientation=np.radians(
                30
            ),  #con 60 grados funciona perfecto, pero las coordenadas cambian. Antes 30
            facecolor=color,
            alpha=0.2,
            edgecolor='k')
        #cambiar radius=2. / 3. , cuando se usa coord_0
        ax.add_patch(hex)
        # Also add a text label
        ax.text(x, y + 0.2, l[0], ha='center', va='center', size=6)
    # Also add scatter points in hexagon centres
    ax.scatter(hcoord, vcoord, c=[c[0].lower() for c in colors], alpha=0.5)
    plt.grid(True)
    plt.savefig("hexagrid.png")
    plt.show()
Пример #29
0
 def figmaker(x, y, i):
     if colors is not None:
         kwargs["color"] = colors[i]
     if patch_type == 'ellipse' or patch_type == 'circle':  # circles are just ellipses
         angle = kwargs['angle'] if 'angle' in kwargs else 0
         fig = Ellipse((x, y), angle=angle, **kwargs)
     elif patch_type == "rect":
         fig = Rectangle([x - kwargs['width'] / 2, y - kwargs['height'] / 2], **kwargs)
     elif patch_type.startswith("poly"):
         edges = int(patch_type[4:])
         fig = RegularPolygon([x, y], numVertices=edges, radius=size, **kwargs)
     else:
         logger.error("Wrong patchtype. Please choose a correct patch type.")
     if infofunc:
         infos.append(infofunc(buses[i]))
     return fig
Пример #30
0
 def _draw_target(self, ax, i, j):
     # clear prev_target for movingTarget
     if hasattr(self.env, 'prev_target') and self.env.prev_target is not None:
         if self.open_count[self.env.prev_target[0], self.env.prev_target[1]] > 0:
             color = self.open_color_map[self.env.get_terrain(*self.env.prev_target).name]
         else:
             color = self.color_map[self.env.get_terrain(*self.env.prev_target).name]
         ax.add_patch(RegularPolygon((self.env.prev_target[0] + 0.5, self.env.prev_target[1] + 0.5),
                                     numVertices=4,
                                     radius=0.5 * np.sqrt(2),
                                     orientation=np.pi / 4,
                                     ec=self.edge_color,
                                     fc=color))
     # draw target
     ax.add_patch(plt.Circle((i + 0.5, j + 0.5), radius=0.25,
                             ec='black', fc='red'))
Пример #31
0
def plot_hex(fig, centers, weights, color_ex=False):
    """Plot an hexagonal grid based on the nodes positions and color the tiles
       according to their weights.

        Args:
            fig (matplotlib figure object): the figure on which the hexagonal grid will be plotted.
            centers (list, float): array containing couples of coordinates for each cell 
                to be plotted in the Hexagonal tiling space.
            weights (list, float): array contaning informations on the weigths of each cell, 
                to be plotted as colors.
            color_ex (bool): if true, plot the example dataset with colors.
            
        Returns:
            ax (matplotlib axis object): the axis on which the hexagonal grid has been plotted.
                
    """

    ax = fig.add_subplot(111, aspect='equal')

    xpoints = [x[0] for x in centers]
    ypoints = [x[1] for x in centers]
    patches = []

    cmap = plt.get_cmap('viridis')

    for x, y, w in zip(xpoints, ypoints, weights):

        facecolor = w if color_ex else cmap(w)

        hexagon = RegularPolygon((x, y),
                                 numVertices=6,
                                 radius=.95 / sqrt(3),
                                 orientation=radians(0),
                                 facecolor=facecolor)
        patches.append(hexagon)

    p = PatchCollection(patches, match_original=True)

    setarray = None if color_ex else np.array(weights)
    p.set_array(setarray)

    ax.add_collection(p)

    ax.axis('off')
    ax.autoscale_view()

    return ax
    def draw_token(cls, token, r, c, ax, height, width, token_scale=1.0):
        if token == EMPTY:
            return None

        if 'arrow' in token:
            edge_color = '#888888'
            face_color = '#AAAAAA'

            drawing = RegularPolygon((c + 0.5, (height - 1 - r) + 0.5),
                                     numVertices=4,
                                     radius=0.5 * np.sqrt(2),
                                     orientation=np.pi / 4,
                                     ec=edge_color,
                                     fc=face_color)
            ax.add_patch(drawing)

        if token == LEFT_ARROW:
            arrow_drawing = FancyArrow(c + 0.75,
                                       height - 1 - r + 0.5,
                                       -0.25,
                                       0.0,
                                       width=0.1,
                                       fc='green',
                                       head_length=0.2)
            ax.add_patch(arrow_drawing)

        elif token == RIGHT_ARROW:
            arrow_drawing = FancyArrow(c + 0.25,
                                       height - 1 - r + 0.5,
                                       0.25,
                                       0.0,
                                       width=0.1,
                                       fc='green',
                                       head_length=0.2)
            ax.add_patch(arrow_drawing)

        else:
            im = TOKEN_IMAGES[token]
            oi = OffsetImage(im,
                             zoom=cls.fig_scale *
                             (token_scale / max(height, width)**0.5))
            box = AnnotationBbox(oi, (c + 0.5, (height - 1 - r) + 0.5),
                                 frameon=False)

            ax.add_artist(box)

            return box