def plot_diagram(conflicts):
    plt.plot(conflicts)
    plt.ylabel("Anzahl der Konflikte")
    plt.yticks(np.arange(0, conflicts[0] + 1, step=1))
    plt.xlabel("Generationen")
    plt.Text("NUMBER_OF_ELITE_LECTURES: " + str(NUMBER_OF_ELITE_LECTURES))
    plt.Text("TOURNAMENT_SELECTION_SIZE: " + str(TOURNAMENT_SELECTION_SIZE))
    plt.Text("MUTATION_RATE: " + str(MUTATION_RATE))
    plt.Text("POPULATION_SIZE: " + str(POPULATION_SIZE))
    plt.show()
コード例 #2
0
ファイル: graph_visualizer.py プロジェクト: RI-SE/BIDAF
 def __init__(self, win, name1, name2, tp, strn):
     self.win = win
     self.fr = name1
     self.to = name2
     self.type = ""
     self.strength = 0.0
     self.istrength = (0.0, 0.0, 0.0)
     self.dstrength = (0.0, 0.0, 0.0)
     self.sstrength = 0.0
     n1 = win.nodes[name1]
     n2 = win.nodes[name2]
     n1.links.append(self)
     if not n1 == n2:
         n2.links.append(self)
     if name1 == name2:
         xdiam = win.xscale() * win.radius * 2
         ydiam = win.yscale() * win.radius * 2
         self.line = mpl.patches.Ellipse(
             (0, 0),
             xdiam,
             ydiam,
             linewidth=win.thickness * self.win.dotwidth,
             fill=False)
     else:
         self.line = plt.Line2D((0, 0), (0, 0),
                                linewidth=win.thickness * self.win.dotwidth)
     self.arrow = [
         plt.Line2D((0, 0), (0, 0),
                    linewidth=win.thickness * self.win.dotwidth),
         plt.Line2D((0, 0), (0, 0),
                    linewidth=win.thickness * self.win.dotwidth)
     ]
     zo = min(n1.circles[0].zorder, n2.circles[0].zorder) - 2
     self.line.zorder = zo
     self.arrow[0].zorder = zo
     self.arrow[1].zorder = zo
     self.text = [
         plt.Text(0, 0, "", fontsize=self.win.fontsz0 * self.win.dotwidth),
         plt.Text(0, 0, "", fontsize=self.win.fontsz0 * self.win.dotwidth)
     ]
     self.text[0].zorder = zo
     self.text[1].zorder = zo
     self.histgr = False
     self.modify(name1, name2, tp, strn)
     tup = (self.fr, self.to) if self.fr < self.to else (self.to, self.fr)
     self.win.links[tup] = self
     win.fig.add_artist(self.line)
     win.fig.add_artist(self.arrow[0])
     win.fig.add_artist(self.arrow[1])
     win.fig.add_artist(self.text[0])
     win.fig.add_artist(self.text[1])
コード例 #3
0
 def draw(self, ax, dy=0, animate=False):
     if animate:
         figures = [
             plt.Line2D([self.x1, self.x2], [self.y1, self.y2],
                        color=self.color)
         ]
         x_middle = (self.x1 + self.x2) / 2.0
         y_middle = (self.y1 + self.y2) / 2.0 - dy
         if self.label:
             figures.append(
                 plt.Text(x_middle,
                          y_middle,
                          self.label,
                          horizontalalignment='center',
                          verticalalignment='center',
                          fontsize=10))
         return figures
     else:
         ax.plot([self.x1, self.x2], [self.y1, self.y2], c=self.color)
         if self.label:
             x_middle = (self.x1 + self.x2) / 2.0
             y_middle = (self.y1 + self.y2) / 2.0 - dy
             ax.text(x_middle,
                     y_middle,
                     self.label,
                     horizontalalignment='center',
                     verticalalignment='center',
                     fontsize=10)
コード例 #4
0
ファイル: graph_visualizer.py プロジェクト: RI-SE/BIDAF
 def __init__(
     self,
     win,
     pos,
     txt,
     state=0,
     fontsz=12,
     statedict={
         0: ('white', 'white'),
         1: ('white', 'black'),
         2: (hsl_color(0.0, 0.0, 0.0), 'black'),
         3: ('black', 'black')
     }):
     self.win = win
     self.pos = pos
     self.state = state
     self.statedict = statedict
     bcol = self.statedict[state]
     bpos = win.trans(tupleadd(pos, (fontsz * 2 / 3, fontsz * 2 / 3)))
     tpos = win.trans(tupleadd(pos, (fontsz * 2, 0)))
     self.bullet = mpl.patches.Ellipse(bpos,
                                       win.xscale() * fontsz,
                                       win.yscale() * fontsz,
                                       facecolor=bcol[0],
                                       edgecolor=bcol[1],
                                       linewidth=fontsz / 6)
     self.text = plt.Text(tpos[0], tpos[1], txt, fontsize=fontsz)
     win.fig.add_artist(self.bullet)
     win.fig.add_artist(self.text)
コード例 #5
0
    def display(self):
        import matplotlib.pyplot as plt
        import math
        import random
        import numpy as np

        ns = len(self.nodes)  # numero de estados
        rs = math.pi / (2 * ns)

        colors = [(random.random(), random.random(), random.random())
                  for state in self.nodes]
        theta = 0
        for state in self.nodes:
            cxpos = 1 * math.cos(math.radians(theta))
            cypos = 1 * math.sin(math.radians(theta))
            txpos = (1 + (2 * rs)) * math.cos(math.radians(theta))
            typos = (1 + (2 * rs)) * math.sin(math.radians(theta))
            stateColor = colors[self.nodes.index(state)]
            invStateColor = tuple([1 - x for x in stateColor])
            c = plt.Circle((cxpos, cypos), rs, color=stateColor)
            t = plt.Text(txpos,
                         typos,
                         state.name,
                         horizontalalignment='center',
                         fontsize=15,
                         verticalalignment='top')
            plt.gcf().gca().add_artist(c)
            plt.gcf().gca().add_artist(t)
            if state.isFinalState:
                finalIndicatorCircle = plt.Circle((cxpos, cypos),
                                                  rs - rs / 10,
                                                  fill=False,
                                                  color=invStateColor)
                plt.gcf().gca().add_artist(finalIndicatorCircle)
            theta = theta + (360 / ns)

        for transition in self.edges:
            fromState, toState = transition.getNodes()
            fromTheta = self.nodes.index(fromState) * (360 / ns)
            toTheta = self.nodes.index(toState) * (360 / ns)
            fromx, fromy = (math.cos(math.radians(fromTheta)),
                            math.sin(math.radians(fromTheta)))
            tox, toy = (math.cos(math.radians(toTheta)),
                        math.sin(math.radians(toTheta)))

            if transition.symbol == '1':
                l = plt.Line2D([fromx - rs / 4, tox - rs / 4],
                               [fromy - rs / 4, toy - rs / 4],
                               5,
                               color=colors[self.nodes.index(fromState)])
                plt.gcf().gca().add_artist(l)
            else:
                l = plt.Line2D([fromx + rs / 4, tox + rs / 4],
                               [fromy + rs / 4, toy + rs / 4],
                               5,
                               linestyle='dashed',
                               color=colors[self.nodes.index(fromState)])
                plt.gcf().gca().add_artist(l)
        plt.axis('off')
        plt.show()
コード例 #6
0
	def draw_neurons(self):
		radius = self.data['neuron_radius']
		for neuron in self.data['neurons']:
			color = 'w'
			if 'color' in neuron:
				color = neuron['color']

			circle = plt.Circle(
				(neuron['x'], neuron['y']),
				radius,
				color=color,
				ec='k',
				zorder=4,
				label='1'
			)
			
			label = neuron['innov']
			if 'label' in neuron:
				label = neuron['label'] + str(label)

			self.ax.add_artist(circle)

			if self.data['print_neurons_txt']:
				txt = plt.Text(
					neuron['x'] - radius * 0.8, neuron['y'] + radius * 1.1,
					label,
					zorder=5)
				self.ax.add_artist(txt)
コード例 #7
0
    def univariate_plots(Source):
        print("Columns that are int32,int64 = ",
              Source.select_dtypes(include=['int32', 'int64']).columns)
        print("Columns that are flaot32,float64 = ",
              Source.select_dtypes(include=['float64']).columns)
        print("Columns that are objects = ",
              Source.select_dtypes(include=['object']).columns)
        a = pandas.Series(
            Source.select_dtypes(include=['int32', 'int64']).columns)
        leng = len(a)
        for j in range(0, len(a)):
            f, axes = matplot.subplots(1, 2, figsize=(10, 10))
            sns.boxplot(Source[a[j]], ax=axes[0])
            sns.distplot(Source[a[j]], ax=axes[1])
            matplot.subplots_adjust(top=1.5, right=10, left=8, bottom=1)

        a = pandas.Series(Source.select_dtypes(include=['float64']).columns)
        leng = len(a)
        for j in range(0, len(a)):
            matplot.Text('Figure for float64')
            f, axes = matplot.subplots(1, 2, figsize=(10, 10))
            sns.boxplot(Source[a[j]], ax=axes[0])
            sns.distplot(Source[a[j]], ax=axes[1])
            matplot.subplots_adjust(top=1.5, right=10, left=8, bottom=1)

        a = pandas.Series(Source.select_dtypes(include=['object']).columns)
        leng = len(a)
        for j in range(0, len(a)):
            matplot.subplots()
            sns.countplot(Source[a[j]])
コード例 #8
0
ファイル: entity_visualizer.py プロジェクト: RI-SE/BIDAF
 def __init__(self, vis, id, pos, sz, sel = False):
     self.vis = vis
     self.id = id
     self.name = str(id)
     self.pos = pos
     self.sqsize = sz
     self.selected = sel
     self.color = 'white'
     xsc = vis.xscale()
     ysc = vis.yscale()
     p1 = vis.trans(self.pos)
     p2 = tupleadd(p1, (xsc, -ysc), 2.0)
     p3 = tupleadd(p1, (xsc, -ysc), -1.0)
     gr1 = hsl_color(0, 0, -0.2)
     gr2 = hsl_color(0, 0, -0.5)
     gr3 = hsl_color(0, 0, 0.3)
     self.txt = plt.Text(p1[0] + (self.sqsize + 10)*xsc, p1[1] + self.sqsize*ysc/3, self.name, ha='left', fontsize=self.vis.fontsz*self.vis.dotwidth)
     r1 = plt.Rectangle(tupleadd(p1, (xsc, -ysc), 1.0), xsc*self.sqsize, ysc*self.sqsize, linewidth=6*self.vis.dotwidth, edgecolor= gr1, facecolor=self.color)
     r2 = plt.Rectangle(p2, xsc*self.sqsize, ysc*self.sqsize, linewidth=3*self.vis.dotwidth, edgecolor= gr2, fill=False)
     r3 = plt.Rectangle(p3, xsc*self.sqsize, ysc*self.sqsize, linewidth=3*self.vis.dotwidth, edgecolor= gr3, fill=False)
     if self.selected:
         r4 = plt.Rectangle(tupleadd(p1, (0, -ysc), 2.0), xsc*(self.sqsize+2), ysc*(self.sqsize+2), linewidth=2*self.vis.dotwidth, edgecolor= gr1, fill=False)
     else:
         r4 = plt.Rectangle(tupleadd(p1, (xsc, 0), 2.0), xsc*(self.sqsize-2), ysc*(self.sqsize-2), linewidth=2*self.vis.dotwidth, edgecolor= gr1, fill=False)
     self.objs = [r1,r2,r3,r4]
     for r in self.objs:
         self.vis.fig.add_artist(r)
     self.vis.fig.add_artist(self.txt)
コード例 #9
0
def draw_grid(grid, size=6, margin=0.02, fontsize=16):
    from matplotlib import pyplot as plt
    cols = len(grid[0])
    rows = len(grid)
    aspect = rows / float(cols)
    fig, ax = plt.subplots(figsize=(6, 6 * aspect))
    fig.subplots_adjust(0, 0, 1, 1)
    ax.set_axis_off()
    fig.patch.set_facecolor("white")

    line_props = dict(transform=ax.transAxes, lw=1, color="#777777")

    width = (1 - 2 * margin) / cols
    height = (1 - 2 * margin) / rows

    for i in np.linspace(margin, 1 - margin, rows + 1):
        line = plt.Line2D([margin, 1 - margin], [i, i], **line_props)
        ax.add_artist(line)

    for i in np.linspace(margin, 1 - margin, cols + 1):
        line = plt.Line2D([i, i], [margin, 1 - margin], **line_props)
        ax.add_artist(line)

    for (r, c), v in np.ndenumerate(grid):
        text = plt.Text(margin + c * width + width * 0.5,
                        margin + (rows - r - 1) * height + height * 0.5,
                        "%s" % v,
                        transform=ax.transAxes,
                        va="center",
                        ha="center",
                        fontsize=fontsize)
        ax.add_artist(text)

    fig.show()
コード例 #10
0
def show_node(node, ax, height, index, font_size):
    if not node:
        return
    x1, y1 = None, None
    if node.left:
        x1, y1, index = show_node(node.left, ax, height - 1, index, font_size)
    x = 100 * index - 50
    y = 100 * height - 50
    if x1:
        plt.plot((x1, x), (y1, y), linewidth=2.0, color='b')
    circle_color = "black" if node.color == "BLACK" else 'r'
    text_color = "beige" if node.color == "BLACK" else 'black'
    ax.add_artist(plt.Circle((x, y), 50, color=circle_color))
    ax.add_artist(
        plt.Text(x,
                 y,
                 node.data,
                 color=text_color,
                 fontsize=font_size,
                 horizontalalignment="center",
                 verticalalignment="center"))
    # print(str(node.val), (height, index))

    index += 1
    if node.right:
        x1, y1, index = show_node(node.right, ax, height - 1, index, font_size)
        plt.plot((x1, x), (y1, y), linewidth=2.0, color='b')

    return x, y, index
コード例 #11
0
ファイル: FBMapDrawApp.py プロジェクト: FredBill1/FBScope
 def _createCircle(self, x, y):
     r = self.get_circle_r(CIRCLE_SIZE)
     circle = plt.Circle((x, y), r, color="black", picker=True)
     label = plt.Text(x + r, y + r, f"({x:.2f}, {y:.2f})", color="black")
     self._ax.add_patch(circle)
     self._ax.add_artist(label)
     self.circles[circle] = label
     self.pointCnt.set(self.pointCnt.get() + 1)
コード例 #12
0
ファイル: solarsystem.py プロジェクト: davidsamu/Spaceship-RL
    def render(self, txt='', plot_orbits=True, plot_trajectory=True):
        """Render current game state."""

        # Init new frame.
        self.init_canvas()
        curr_frame_artists = []

        # Star.
        astar = plt.Circle(self.star.get_pos(), self.star.size,
                           fc=self.star.color)
        curr_frame_artists.append(astar)

        # Planets.
        aplanets = [plt.Circle(planet.get_pos(), planet.size,
                               fc=planet.color) for planet in self.planets]
        [curr_frame_artists.append(aplanet) for aplanet in aplanets]

        # Orbits.
        aorbits = [plt.Circle([0, 0], planet.r, fc='none', ec=planet.color)
                   for planet in self.planets]
        [aorbit.set_visible(plot_orbits) for aorbit in aorbits]
        [curr_frame_artists.append(aorbit) for aorbit in aorbits]

        # Beacon.
        abeacon = plt.Circle(self.beacon.get_pos(), self.beacon.size,
                             fc=self.beacon.color)
        curr_frame_artists.append(abeacon)

        # Spaceship.
        aship = plt.Circle(self.ship.get_pos(),
                           self.ship.size, fc=self.ship.color)
        curr_frame_artists.append(aship)

        # Render trajectory of spaceship.
        xvec, yvec = zip(*self.ship.trajectory)
        traj = self.ax.plot(xvec, yvec, color='grey', lw=1, zorder=0)[0]
        traj.set_visible(plot_trajectory)
        curr_frame_artists.append(traj)

        # Add some text info to display.
        x, y = self.xmax, self.ymin
        label = txt + 'step {}'.format(self.ep_nsteps)
        label += '\nR_curr: {:.3f}'.format(self.calc_reward())
        label += '\nR_total: {:.3f}'.format(self.total_ep_reward)
        text = plt.Text(x, y, label, fontsize='small', va='bottom', ha='right',
                        color='white')
        curr_frame_artists.append(text)

        # Add all artists of current frame to display.
        for artist in curr_frame_artists:
            self.ax.add_artist(artist)

        # Add artists for animation.
        self.animation.append(curr_frame_artists)
コード例 #13
0
 def mohr(self):
     a, b, c = self.bdchinh()
     A = abs(a)
     C = abs(c)
     fig, ax = plt.subplots()
     ax.set_xlim((-(A + C), (A + C)))
     ax.set_ylim((-(A + C), (A + C)))
     ax.add_artist(Circle(((a + c) / 2, 0), (a - c) / 2))
     ax.add_artist(Circle(((b + c) / 2, 0), (b - c) / 2, color="Red"))
     ax.add_artist(Circle(((a + b) / 2, 0), (a - b) / 2, color="Black"))
     plt.Text()
     plt.show()
    def __init__(self):

        self.fig = plt.figure(figsize=(5, 5))
        self.fig.canvas.set_window_title(u'数独求解器')
        ax = self.fig.add_subplot(1, 1, 1)
        ax.set_aspect("equal")
        ax.set_axis_off()
        self.fig.subplots_adjust(0.0, 0.0, 1, 1)
        self.fig.patch.set_facecolor("white")

        for i in range(10):
            loc = 0.05 + i * 0.1
            lw = 2 if i % 3 == 0 else 1
            color = "k" if lw > 1 else "#777777"
            line = plt.Line2D([0.05, 0.95], [loc, loc],
                              transform=ax.transAxes,
                              color=color,
                              lw=lw)
            ax.add_artist(line)
            line = plt.Line2D([loc, loc], [0.05, 0.95],
                              transform=ax.transAxes,
                              color=color,
                              lw=lw)
            ax.add_artist(line)

        self.cells = {}
        for col, row in np.broadcast(*np.ogrid[:9:1, :9:1]):
            x = 0.1 + col * 0.1
            y = 0.9 - row * 0.1
            text = plt.Text(x,
                            y,
                            "0",
                            transform=ax.transAxes,
                            va="center",
                            ha="center",
                            fontsize=16)
            ax.add_artist(text)
            self.cells[row, col] = text

        self.rect = plt.Rectangle((0.05, 0.05),
                                  0.1,
                                  0.1,
                                  transform=ax.transAxes,
                                  alpha=0.3)
        ax.add_artist(self.rect)

        self.current_pos = (0, 0)
        self.set_current_cell((0, 0))
        self.setted_cells = {}
        self.solver = SudokuSolver()
        self.calc_solution()
        self.fig.canvas.mpl_connect("key_press_event", self.on_key)
コード例 #15
0
ファイル: metromap.py プロジェクト: linnarsson-lab/cytograph2
def metromap(ds: loompy.LoomConnection,
             dsagg: loompy.LoomConnection,
             out_file: str = None,
             embedding: str = "TSNE") -> None:
    ga = dsagg.col_graphs.GA
    n_components, labels = sparse.csgraph.connected_components(
        csgraph=ga, directed=False, return_labels=True)
    labels = renumber_components(labels)
    aspect_ratio = (
        ds.ca[embedding][:, 0].max() - ds.ca[embedding][:, 0].min()) / (
            ds.ca[embedding][:, 1].max() - ds.ca[embedding][:, 1].min())
    plt.figure(figsize=(10 * aspect_ratio, 10))
    ax = plt.subplot(111)
    plt.scatter(ds.ca[embedding][:, 0],
                ds.ca[embedding][:, 1],
                s=10,
                lw=0,
                c="lightgrey")
    r = ((ds.ca[embedding][:, 0].max() - ds.ca[embedding][:, 0].min()) +
         (ds.ca[embedding][:, 1].max() - ds.ca[embedding][:, 1].min())) / 100
    for c in np.unique(ds.ca.Clusters):
        ls = ":" if labels[c] == -1 else "-"
        ax.add_artist(
            plt.Circle((dsagg.ca[embedding][c, 0], dsagg.ca[embedding][c, 1]),
                       lw=2,
                       radius=r,
                       fill=True,
                       linestyle=ls,
                       fc="white",
                       ec="black",
                       alpha=0.8))
        ax.add_artist(
            plt.Text(dsagg.ca[embedding][c, 0],
                     dsagg.ca[embedding][c, 1],
                     str(c),
                     fontname="Verdana",
                     fontsize=11,
                     zorder=1,
                     va="center",
                     ha="center"))
    lc = LineCollection(zip(dsagg.ca[embedding][ga.row],
                            dsagg.ca[embedding][ga.col]),
                        linewidths=6,
                        color=tube_colors[labels[ga.row]],
                        alpha=1,
                        zorder=1)
    ax.add_collection(lc)
    plt.axis("off")
    if out_file is not None:
        plt.savefig(out_file, dpi=144)
        plt.close()
コード例 #16
0
ファイル: mlutils.py プロジェクト: MartinEliasQ/20191.DL
def draw_neural_net(ax, left, right, bottom, top, layer_sizes):
    '''
    Draw a neural network cartoon using matplotilb.
    
    :usage:
        >>> fig = plt.figure(figsize=(12, 12))
        >>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2])
    
    :parameters:
        - ax : matplotlib.axes.AxesSubplot
            The axes on which to plot the cartoon (get e.g. by plt.gca())
        - left : float
            The center of the leftmost node(s) will be placed here
        - right : float
            The center of the rightmost node(s) will be placed here
        - bottom : float
            The center of the bottommost node(s) will be placed here
        - top : float
            The center of the topmost node(s) will be placed here
        - layer_sizes : list of int
            List of layer sizes, including input and output dimensionality
    '''
    n_layers = len(layer_sizes)
    v_spacing = (top - bottom)/float(max(layer_sizes))
    h_spacing = (right - left)/float(len(layer_sizes) - 1)
    # Nodes
    for n, layer_size in enumerate(layer_sizes):
        layer_top = v_spacing*(layer_size)/2. + (top + bottom)/2.
        for m in xrange(layer_size+(1 if n<layer_size else 0) ):
            color = "red" if n==0 else "blue" if n==len(layer_sizes)-1 else "gray"
            ec = "black"
            alpha = 1.
            if m==layer_size:
                ec = "gray"
                color = "white"
            circle = plt.Circle((n*h_spacing + left, layer_top - m*v_spacing), v_spacing/4.,
                                color=color, ec=ec, zorder=4, alpha=alpha)
            ax.add_artist(circle)
            if m==layer_size:
                text = plt.Text(n*h_spacing + left - .015, layer_top - m*v_spacing - .015, "1", zorder=5)
                ax.add_artist(text)
    # Edges
    for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
        layer_top_a = v_spacing*(layer_size_a)/2. + (top + bottom)/2.
        layer_top_b = v_spacing*(layer_size_b)/2. + (top + bottom)/2.
        for m in xrange(layer_size_a+1):
            for o in xrange(layer_size_b):
                color = "gray" if m==layer_size_a else "black"
                line = plt.Line2D([n*h_spacing + left, (n + 1)*h_spacing + left],
                                  [layer_top_a - m*v_spacing, layer_top_b - o*v_spacing], c=color, alpha=.5)
                ax.add_artist(line)
コード例 #17
0
ファイル: graph_visualizer.py プロジェクト: RI-SE/BIDAF
 def __init__(self, win, name1, name2, name3, tp, strn):
     self.win = win
     self.name1 = name1
     self.name2 = name2
     self.name3 = name3
     self.type = ""
     self.istrength = (0.0, 0.0, 0.0)
     self.dstrength = (0.0, 0.0, 0.0)
     self.cnum = 20
     self.clst = [
         np.cos(i * np.pi / (2 * self.cnum)) for i in range(self.cnum + 1)
     ]
     n1 = win.nodes[name1]
     n2 = win.nodes[name2]
     n3 = win.nodes[name3]
     n1.hlinks.append(self)
     n2.hlinks.append(self)
     n3.hlinks.append(self)
     self.path = mpl.patches.Polygon([[0, 0], [0, 0], [0, 0]],
                                     fill=True,
                                     closed=True)
     self.text = [
         plt.Text(0, 0, "", fontsize=self.win.fontsz0 * self.win.dotwidth),
         plt.Text(0, 0, "", fontsize=self.win.fontsz0 * self.win.dotwidth)
     ]
     zo = min(n1.circles[0].zorder, n2.circles[0].zorder) - 2
     self.path.zorder = zo
     self.text[0].zorder = zo
     self.text[1].zorder = zo
     self.histgr = False
     self.modify(tp, strn)
     self.updatepathpos()
     self.win.hlinks[tuple(sorted([self.name1, self.name2,
                                   self.name3]))] = self
     win.fig.add_artist(self.path)
     win.fig.add_artist(self.text[0])
     win.fig.add_artist(self.text[1])
コード例 #18
0
    def add_label(self, text, where='bottom'):
        d = {
            'left': self.left_label,
            'right': self.right_label,
            'top': self.top_label,
            'bottom': self.bottom_label,
            'title': self.top_title
        }
        r = d[where]
        if where == 'title':
            fs = plt.rcParams['axes.titlesize']
        else:
            fs = plt.rcParams['xtick.labelsize']

        if where in ('left', 'right'):
            rotation = 'vertical'
            txt = plt.Text(0,
                           0,
                           text=text,
                           transform=self.figure.transFigure,
                           rotation=rotation,
                           va='bottom',
                           ha='left',
                           fontsize=fs)
        else:
            rotation = 'horizontal'
            txt = plt.Text(0,
                           0,
                           text=text,
                           transform=self.figure.transFigure,
                           rotation=rotation,
                           va='bottom',
                           ha='left',
                           fontsize=fs)

        r.set_mpl_text(txt)
コード例 #19
0
 def plot(self, phasors):
     """
     Plot phasors and label phasors. The label correspond to the index
     of the phasor list. Phasor from diferent color (named in the legend)
     must be put in different sublists, 
     e.g. [[uncalibrated phasors], [calibrated phasors]].
     :param phasors:
     """
     for color, phasor_list in zip(self.colors, phasors):
         for i, phasor in enumerate(phasor_list):
             phr = np.real(phasor)
             phi = np.imag(phasor)
             arrow = plt.Arrow(0, 0, phr, phi, width=0.05, color=color)
             text = plt.Text(phr, phi, 'a' + str(i), color=color)
             self.ax.add_artist(arrow)
             self.ax.add_artist(text)
コード例 #20
0
def plot_calibration_phasors(fig, ax, uncal_phasors, cal_phasors):
    """
    Plot a list of uncalibrated and calibrated phasors (complex numbers)
    a arrows in a unit circle.
    """
    colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][:2]
    for color, phasor_list in zip(colors, [uncal_phasors, cal_phasors]):
        for i, phasor in enumerate(phasor_list):
            phr = np.real(phasor)
            phi = np.imag(phasor)
            arrow = plt.Arrow(0, 0, phr, phi, width=0.05, color=color)
            text = plt.Text(phr, phi, 'a'+str(i), color=color)
            ax.add_artist(arrow)
            ax.add_artist(text)
    
    fig.canvas.draw()
コード例 #21
0
ファイル: pddm5.py プロジェクト: 489-502/tftp_ui
    def unpackIndiMsg(self, msgId, buf):
        volt = []
        cur_in1 = []
        cur_out1 = []
        cur_in2 = []
        cur_out2 = []

        INDI_MSG_BODY_SIZE = self.getMsgDic()[msgId]['len']
        INDI_MSG_SIZE = self.MSG_HEAD_SIZE + INDI_MSG_BODY_SIZE

        #Get the voltage in each message
        for i in range(len(buf) / INDI_MSG_SIZE):
            msgbody = self.unpackAppMsg(
                msgId, buf[i * INDI_MSG_SIZE + self.MSG_HEAD_SIZE:(i + 1) *
                           INDI_MSG_SIZE])
            #print msgbody
            volt.append(msgbody[0])
            cur_in1.append(msgbody[1])
            cur_out1.append(msgbody[2])
            cur_in2.append(msgbody[3])
            cur_out2.append(msgbody[4])

        #Calculate the voltage and current RMS
        for i in range(len(volt)):
            volt[i] *= 0.09847
            cur_in1[i] *= 0.009825
            cur_out1[i] *= 0.009825
            cur_in2[i] *= 0.009825
            cur_out2[i] *= 0.009825

        #Plot the voltage
        plt.subplot(211)
        plt.title('Indication Power Voltage')
        plt.ylabel('Voltage RMS: V')
        plt.axis([0, 100, 0, 200])
        plt.plot(np.array(volt), 'r')
        plt.subplot(212)
        plt.title('Indication Current')
        plt.ylabel('Current RMS: mA')
        plt.axis([0, 100, 0, 20])
        plt.Text('Red: R_IN; Green: R_OUT; Blue: N_IN; Pupple: N_OUT')
        plt.plot(np.array(cur_in1), 'r', label='R_IN')
        plt.plot(np.array(cur_out1), 'g', label='R_OUT')
        plt.plot(np.array(cur_in2), 'b', label='N_IN')
        plt.plot(np.array(cur_out2), 'y', label='N_OUT')
        plt.legend(loc='lower right', fancybox=True, shadow=True)
        plt.show()
コード例 #22
0
def output_state(cell, t, Lmax):
	# Output an image frame and print the coordinates to stdout

	# Plot:
	fig = plt.gcf()
	ax = plt.gca()
	ax.cla()
	# Uncomment to draw grid:
	#ax.grid(b=True, which='major')
	# Draw boundaries
	fig.gca().add_artist(plt.Rectangle((0,0),Lmax[0],Lmax[1],fill=False, color='0.75'))

	# Draw cells
	for i in xrange(len(cell)):
		col = cell[i].plot_colour()
		s = cell[i].steric_radius
		if s == 0:
			s=2
		cx=cell[i].pos[0]
		cy=cell[i].pos[1]
		fig.gca().add_artist(plt.Circle((cx,cy),s,color=col,fill=True))

	bufferx, buffery = 0.25*Lmax[0], 0.25*Lmax[1]
	if bufferx < 10:
		bufferx = 10
	if buffery < 10:
		buffery = 10
	if bufferx > 100:
		bufferx = 100
	if buffery > 100:
		buffery = 100
	# Add label
	fig.gca().add_artist(plt.Text(x=(Lmax[0]*0.75),y=(Lmax[1]+buffery*0.5), text=str(t), \
		horizontalalignment='right', size='16'))
	ax.set_xlim(-bufferx, Lmax[0]+bufferx)
	ax.set_ylim(-buffery, Lmax[1]+buffery)
	ax.set_aspect(1)
	ax.invert_yaxis()
	fig.savefig('config-'+"{0:05d}".format(int(t))+'.png', dpi=150, bbox_inches='tight')

	# Print coordinates
	for id in xrange(len(cell)):
		contraction = 0
		if cell[id].actomyosin_contraction:
			contraction = 1
		print t, cell[id].type, id, cell[id].pos[0], cell[id].pos[1], contraction
	print "\n"
コード例 #23
0
ファイル: neat.py プロジェクト: Mimer29or40/PixelEngine
def fitness_plot(fitness, segments=4):
    canvas = plt.gcf().canvas
    plt.plot(fitness)
    plt.title('Fitness over time')
    plt.ylabel('Fitness')
    plt.xlabel('Generation')
    locations, labels = [], []
    for i in range(segments + 1):
        loc = int(i / segments * len(fitness)) - 1
        locations.append(loc)
        labels.append(plt.Text(loc, 0, str(loc + 1)))
    plt.xticks(locations, labels)
    canvas.draw()
    return Image.fromarray(
        np.roll(np.fromstring(canvas.tostring_argb(), dtype=np.uint8).reshape(
            (*canvas.get_width_height()[::-1], 4)),
                3,
                axis=2))
コード例 #24
0
def add_labels(ax, m, label_coordinates, label_positioning, fontsize=13):
    """
    Add labels to a basemap ``m`` on the given ``ax``.

    Parameters
    ----------
    label_coordinates : dict
        Dict of coordinates for each label in the form of
        {label: (lat, lon)}
    label_positioning : dict
        Dict of positions for each label in the form {label: position},
        where position can be 'c' (center), 'r' (right), 'l' (left), or
        'b' (bottom)

    """
    align_x = 25000
    align_y = 35000
    for zone, pos in label_positioning.items():
        lat, lon = label_coordinates[zone]
        x, y = m(lon, lat)
        if pos == 'c':
            # no x/y adjustment for central labels..
            ha = 'center'
        if pos == 'l':
            x -= align_x
            ha = 'right'
        if pos == 'r':
            x += align_x
            ha = 'left'
        if pos == 'b':
            y -= align_y
            ha = 'center'
        ax.add_artist(
            plt.Text(x,
                     y,
                     zone,
                     fontsize=fontsize,
                     color='black',
                     backgroundcolor='white',
                     horizontalalignment=ha,
                     verticalalignment='bottom',
                     zorder=10))
    return ax
コード例 #25
0
ファイル: gte.py プロジェクト: AtomicGu/LeetCodeX
    def __init__(self, x, y, ax: plt.Axes, *, radius=0.05, index=None):
        self.circle = plt.Circle(
            (x, y),
            radius,
            lw=2,
            edgecolor="#84affa",
            facecolor="#c6e5ff",
        )
        self.ax = ax
        ax.add_patch(self.circle)

        if index is None:
            index = str(id(self) % 100)
        self.index = plt.Text(x, y, index, size="small")
        ax.add_artist(self.index)

        self.tos = {}
        self.frs = {}
        return
コード例 #26
0
def lignes(charges: List[Charge], n: int, Xmax: float, Ymax: float, dt: float,
           Dmin: float):

    debut = perf_counter()

    for i, (Qi, Ri) in enumerate(charges, 1):
        debut_c = perf_counter()

        Rx, Ry = Ri.real, Ri.imag

        if Qi > 0:
            color = 'r'
            signe = -1

        else:
            color = 'b'
            signe = 1

        txt = plt.Text(Rx,
                       Ry,
                       round(abs(Qi), 2),
                       ha="center",
                       va="center",
                       color='w',
                       bbox={
                           'boxstyle': 'circle',
                           'color': color
                       })
        ax.add_artist(txt)

        for point_couronne in voisinage(Ri, Dmin, n):
            X, Y = zip((Rx, Ry),
                       *ligne(point_couronne, charges, Xmax, Ymax, dt, Dmin,
                              signe))
            ax.plot(X, Y, zorder=1)

        fin_c = perf_counter()

        print(f"Charge {i}/{len(charges)}, {(fin_c - debut_c):.3f}s")

    fin = perf_counter()
    print(f"Total: {(fin - debut):.3f}s")
コード例 #27
0
    def generate_freq(self):
        '''
        Compute and draw frequential antenna pattern
        '''
        self.clear_freq()
        self.points_freq = smos.get_baselines_dict(self.points_spatial)

        # Draw circles representing antennas
        for key in self.points_freq:
            x, y = smos.key2freq(key)

            # From distance between antennas to sampling freqs.
            x = x * q / lamb
            y = y * q / lamb

            circle = plt.Circle((x, y), lamb / 2, color='b', alpha=0.5)
            self.ax_freq.add_artist(circle)

            text_artist = plt.Text(x, y, self.points_freq[key], fontsize=10)
            self.ax_freq.add_artist(text_artist)
コード例 #28
0
    def draw(self, ax, dy=0, animate=False):
        if animate:
            figures = [
                plt.Line2D([self.x], [self.y], marker='o', color=self.color)
            ]
            if self.label:
                figures.append(
                    plt.Text(self.x,
                             self.y - dy,
                             self.label,
                             horizontalalignment='center',
                             verticalalignment='center',
                             fontsize=10))

            return figures
        else:
            ax.plot([self.x], [self.y], 'o', c=self.color)
            if self.label:
                ax.text(self.x,
                        self.y - dy,
                        self.label,
                        horizontalalignment='center',
                        verticalalignment='center',
                        fontsize=10)
コード例 #29
0
    ax = fig.gca()

    for j in range(nBodies):

        alpha = 0.2 if j <= 2 else 0.9

        disk = plt.Circle((body.ra[j].value, body.dec[j].value),
                          koangles[j].value,
                          color=colors[j],
                          alpha=alpha)

        ax.add_artist(disk)

        ax.add_artist(
            plt.Text(text=names[j], x=body.ra[j].value, y=body.dec[j].value))

        # disk underflows left edge of plot window: replot on right

        if body.ra[j].value < koangles[j].value:

            disk = plt.Circle((body.ra[j].value + 360.0, body.dec[j].value),
                              koangles[j].value,
                              color=colors[j],
                              alpha=alpha)

            ax.add_artist(disk)

        # disk overflows right edge of plot window: replot on left

        if body.ra[j].value > 360.0 - koangles[j].value:
コード例 #30
0
 def print_iso_name_annotation(annotate_hole,
                               angle: float,
                               size: float,
                               inner_sizes: bool = True,
                               debug: bool = False):
     nonlocal ax
     nonlocal lim
     nonlocal _text_boxes
     nonlocal max_hole_type
     if inner_sizes and isinstance(
             hole,
             max_hole_type) and max_hole_type._STD_DIAM >= 0.175 * lim:
         _sm = 0.56
     else:
         _sm = 1.0
     if annotate_hole.name is None:
         name = type(annotate_hole).__name__
     else:
         name = annotate_hole.name
     factor = math.cos(angle), math.sin(angle)
     text_point = annotate_hole.pos[0] + (_sm * annotate_hole.diam / 2 + size * lim) * factor[0], \
         annotate_hole.pos[1] + (_sm * annotate_hole.diam / 2 + size * lim) * factor[1]
     if factor[0] >= 0.0:
         tb_x = text_point[0] - 0.025 * lim, text_point[
             0] + 0.0195 * lim * len(name)
         _m = 1.0
     else:
         tb_x = text_point[0] - 0.0195 * lim * len(
             name) - 0.022 * lim, text_point[0]
         _m = 0.1
     if factor[1] >= 0.0:
         tb_y = text_point[1] - 0.0125 * lim, text_point[
             1] + 0.0275 * lim
     else:
         tb_y = text_point[1] - 0.03 * lim, text_point[1] + 0.0125 * lim
     text_box = *tb_x, *tb_y
     if not (inner_sizes and isinstance(hole, max_hole_type)):
         if self._areatree.has_intersection_with_rectangle(
                 text_box[0] - 0.075 * lim * _m, *text_box[1:]):
             return None
     for tb in _text_boxes:
         if box_intersection(text_box, tb):
             return None
     if out_of_plita_range(text_box):
         return None
     if text_box[3] > 0.0 > text_box[2]:
         return None
     if debug:
         ax.add_artist(
             plt.Rectangle((text_box[0], text_box[2]),
                           (text_box[1] - text_box[0]),
                           (text_box[3] - text_box[2]),
                           color='red',
                           alpha=0.3))
     if text_box[1] > 0.0 > text_box[0]:
         ax.add_artist(
             plt.Line2D(
                 (0.0, 0.0),
                 (text_box[2] - lim * 0.011, text_box[3] + lim * 0.01),
                 color='white',
                 linewidth=0.35))
     _text_boxes.append(text_box)
     ax.add_artist(
         plt.Text(text_box[0],
                  text_box[2],
                  name,
                  fontsize=6,
                  fontproperties=GOST_FONT,
                  fontweight="light"))
     return True