Exemplo n.º 1
0
    def run(self, results):
        par = self.getValueOfParameter("parameter")
        i = int(self.getValueOfParameter("iteration number"))
        title = self.getValueOfParameter("title")

        if(par==""):
            return False
        
        if(i >= results.__len__()):
            return False
        
        dialogform = Dialog(QApplication.activeWindow())
        fig = Figure((5.0, 4.0), dpi=100)
        ax = SubplotZero(fig, 1, 1, 1)
        fig.add_subplot(ax)

        for n in ["top", "right"]:
            ax.axis[n].set_visible(False)
            
        for n in ["bottom", "left"]:
            ax.axis[n].set_visible(True)
        
        x = results[i].getResults(par)   
        
        if(not(x.__len__())):
            return False
        
        ax.boxplot(x, notch=0, sym='+', vert=1, whis=1.5)
        
        ax.set_title(title)
        dialogform.showFigure(fig)
        return True
Exemplo n.º 2
0
def _blank_plot(domain, ran):
    # make the plot
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    # thicken the axis lines
    ax.axhline(linewidth=1.7, color="k")
    ax.axvline(linewidth=1.7, color="k")

    x_lower, x_upper = int(domain.left), int(
        domain.right)  # needs to be changed, is just a temporary type changer
    y_lower, y_upper = int(ran.left), int(ran.right)

    # remove tick lines on the axes
    plt.xticks([])
    plt.yticks([])
    plt.ylim(y_lower, y_upper)
    plt.xlim(x_lower, x_upper)

    # add axes labels
    ax.text(1.05,
            0,
            r'$x$',
            transform=BlendedGenericTransform(ax.transAxes, ax.transData),
            va='center')
    ax.text(0,
            1.05,
            r'$y$',
            transform=BlendedGenericTransform(ax.transData, ax.transAxes),
            ha='center')

    # end-of-axis arrows
    x_width = (abs(plt.xlim()[0]) + abs(plt.xlim()[1]))
    y_width = (abs(plt.ylim()[0]) + abs(plt.ylim()[1]))
    plt.arrow(plt.xlim()[1],
              -0.003,
              0.00000000001,
              0,
              width=x_width * 0.0015 * 0.5,
              color="k",
              clip_on=False,
              head_width=y_width * 0.12 / 7,
              head_length=x_width * 0.024 * 0.5)
    plt.arrow(0.003,
              plt.ylim()[1],
              0,
              0.00000000001,
              width=y_width * 0.0015 * 0.5,
              color="k",
              clip_on=False,
              head_width=x_width * 0.12 / 7,
              head_length=y_width * 0.024 * 0.5)

    # only show cartesian axes
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
Exemplo n.º 3
0
	def __init__(self):
		self.fig = plt.figure(1)
		self.ax = SubplotZero(self.fig,111)
		self.fig.add_subplot(self.ax)

		for direction in ["xzero","yzero"]:
			self.ax.axis[direction].set_axisline_style("-|>")
			self.ax.axis[direction].set_visible(True)

		for direction in ["left","right","bottom","top"]:
			self.ax.axis[direction].set_visible(False)
Exemplo n.º 4
0
def make_zerocross_axes(figsize, loc):
    fig = plt.figure(figsize=figsize)
    ax = SubplotZero(fig, loc)
    ax.set_aspect("equal")
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        axis = ax.axis[direction]
        axis.set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    return ax
Exemplo n.º 5
0
 def tell_winner(self, winner, *args):
     if self.show_text:
         print winner, "has won the game!"
     if not self.run_trials: return
     if self.graph:
         from mpl_toolkits.axes_grid.axislines import SubplotZero
         import matplotlib.pyplot as plt
         fig = plt.figure(1)
         ax = SubplotZero(fig, 111)
         fig.suptitle("Winrate of %s over time"%(self.stats.keys()[0]))
         fig.add_subplot(ax)
         ax.plot(self.stats.values()[0])
         plt.show()
     print self.stats.values()[0]
Exemplo n.º 6
0
def plot(points):
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    plt.ylim([-10, 10])
    plt.xlim([-10, 10])
    ax.plot(*zip(*points), marker='o', color='r', ls='')
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
    plt.show()
Exemplo n.º 7
0
def test_m_n_computation(obj_img, theta, Nx, Ny, dx, dy, Nt, Nr, dr):
    
    bx = -Nx/2 * dx 
    by = -Ny/2 * dy 
    xmin = -(Nx-1)/2.0*dx
    ymin = -(Ny-1)/2.0*dy
    
    legend_list = []
    fig = plt.figure(figsize=(8,8))
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    plt.imshow(obj_img, cmap=plt.cm.gray, interpolation='none', \
                        extent=[bx,-bx, by, -by], alpha=0.5)
    for t in np.arange(Nr):   
        if np.sin(theta) < 1.0/np.sqrt(2):
            data = test_n_computation(theta, t, Nx, Ny, dx, dy, Nt, Nr, dr)
        else:
            data = test_m_computation(theta, t, Nx, Ny, dx, dy, Nt, Nr, dr)
        #rdata = np.round(data)
        plt.plot(data[0,:]*dx+xmin, data[1,:]*dy+ymin,'*-', linewidth = 3 )  
        legend_list.append('(t=' + str(t) + ')')
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
    ax.xaxis.set_ticks(np.arange(-Nx,Nx,2))
    ax.yaxis.set_ticks(np.arange(-Ny,Ny,2))
    plt.axis('equal')
    plt.grid(True)
    plt.legend(legend_list)
    plt.title('Angle: ' + str(theta*180/np.pi))
Exemplo n.º 8
0
def plot_func(a, b, c, out_putline):
    '''Plot the line function in a coordinate axis

        Parameters:
        a -- The coefficient for y in the standard for Ay + Bx = C
        b -- The coefficient for x in the standard for Ay + Bx = C
        c -- The constanct C in the standard for Ay + Bx = C
        out_putline -- The string of the standard form Ay + Bx = C
    '''

    # Unable to plot if the coefficient of x or y equals to 0
    if b == 0:
        sys.stderr.write('Unable to plot a vertical line!!!\n')
        sys.exit(1)

    if a == 0:
        sys.stderr.write('Unable to plot a horizontal line!!!\n')
        sys.exit(1)

    # General steps to generate an axis
    try:
        fig = plt.figure(1)
        ax = SubplotZero(fig, 111)
        fig.add_subplot(ax)
    except Exception, e:
        sys.stderr.write('Unable to use matplotlib!!!\n')
        sys.exit(1)
Exemplo n.º 9
0
def test():
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = np.linspace(-0.5, 1., 100)
    ax.plot(x, np.sin(x * np.pi))

    plt.show()
Exemplo n.º 10
0
def setup_two_axes_subplot(fig, m, n, curr_plot_num, invisible=["bottom", "top", "right"]):
    ax = SubplotZero(fig, m, n, curr_plot_num)
    fig.add_subplot(ax)
    ax.axis["xzero"].set_visible(True)
    for n in invisible:
        ax.axis[n].set_visible(False)
    return ax
Exemplo n.º 11
0
def make_zerocross_axes(figsize, loc):
    from matplotlib import pyplot as plt
    from mpl_toolkits.axes_grid.axislines import SubplotZero

    fig = plt.figure(figsize=figsize)
    ax = SubplotZero(fig, loc)
    ax.set_aspect("equal")
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        axis = ax.axis[direction]
        axis.set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    return ax
Exemplo n.º 12
0
 def plot_L(self):
     fig = plt.figure(1)
     ax = SubplotZero(fig, 111)
     fig.add_subplot(ax)
     for el in self.L:
         self.plot_box(X=el, index=0, this_color='blue', canvas=ax)
     ax.set_xlim(-15., 15.)
     ax.set_ylim(-15., 15.)
     ax.axis('equal')
     plt.show()
    def plotAxis(self, matrix):
        #funct = gvbars(delta=0.05, color=color.blue)
        #for i in range(0, len(matrix[0])):
        #    funct.plot(pos=(0,matrix[0][i]))

        #pylab.scatter(3,4, s=100 ,marker='o', c=color.green)
        #pylab.show()

        fig = plt.figure(1)
        ax = SubplotZero(fig, 111)
        fig.add_subplot(ax)
        flattenMatrix = np.transpose(matrix).flatten()
        x = np.linspace(0., 10., len(flattenMatrix))
        print 'x ' + str(x)
        print 'matrix: ' + str(np.transpose(matrix).flatten())
        #ax.plot(x, np.sin(x*np.pi), linewidth=2.0)
        ax.plot(matrix, 0, linewidth=2.0)
        plt.show()
Exemplo n.º 14
0
def make_zerocross_axes(figsize, loc):
    from matplotlib import pyplot as plt
    from mpl_toolkits.axes_grid.axislines import SubplotZero


    fig = plt.figure(figsize=figsize)
    ax = SubplotZero(fig, loc)
    ax.set_aspect("equal")
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        axis = ax.axis[direction]
        axis.set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    return ax
Exemplo n.º 15
0
def make_plot_ax():
    fig = figure(figsize=(6, 5));
    ax = SubplotZero(fig, 111); fig.add_subplot(ax)
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
    xlim(-0.1, 2.1); ylim(xlim())
    ticks = [0.5 * i for i in range(1, 5)]
    labels = [str(i) if i == int(i) else "" for i in ticks]
    ax.set_xticks(ticks); ax.set_yticks(ticks)
    ax.set_xticklabels(labels); ax.set_yticklabels(labels)
    ax.axis["yzero"].set_axis_direction("left")
    return ax
Exemplo n.º 16
0
def subplots():
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
    return fig, ax
Exemplo n.º 17
0
def make_plot_ax():
    fig = figure(figsize=(6, 5))
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
    xlim(-0.1, 2.1)
    ylim(xlim())
    ticks = [0.5 * i for i in range(1, 5)]
    labels = [str(i) if i == int(i) else "" for i in ticks]
    ax.set_xticks(ticks)
    ax.set_yticks(ticks)
    ax.set_xticklabels(labels)
    ax.set_yticklabels(labels)
    ax.axis["yzero"].set_axis_direction("left")
    return ax
Exemplo n.º 18
0
    def run(self, results):
        par1 = self.getValueOfParameter("parameter 1")
        par2 = self.getValueOfParameter("parameter 2")
        title = self.getValueOfParameter("title")
        
        if(par1==""):
            return False
        
        if(par2==""):
            return False
        
        x = pycalimero.doublevector();
        y = pycalimero.doublevector();

	for i in results:
	    x.append(i.getResults(par1)[0])
	    y.append(i.getResults(par2)[0])

        dialogform = Dialog(QApplication.activeWindow())
        fig = Figure((5.0, 4.0), dpi=100)
        ax = SubplotZero(fig, 1, 1, 1)
        fig.add_subplot(ax)

        for n in ["top", "right"]:
            ax.axis[n].set_visible(False)
            
        for n in ["bottom", "left"]:
            ax.axis[n].set_visible(True)   
        
        if(not(x.__len__())):
            return False
        
        if(not(y.__len__())):
            return False
        
        ax.plot (x, y, '.')
        ax.set_title(title)
        
        dialogform.showFigure(fig)
        return True
Exemplo n.º 19
0
def graphWaveSamples(samples):
    y = [struct.unpack('h', i)[0] for i in samples]
    #print y
    print "max:", max(y)
    print "min:", min(y)
    print "avg:", sum(y)/float(len(y))
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)


    x = range(len(y))
    ax.plot(x, y)

    plt.show()
Exemplo n.º 20
0
    def plotUnitCircle(p):
        """ plot some 2D vectors with p-norm < 1 """
        fig = plt.figure(1)
        ax = SubplotZero(fig, 111)
        fig.add_subplot(ax)

        for direction in ["xzero", "yzero"]:
            ax.axis[direction].set_axisline_style("-|>")
            ax.axis[direction].set_visible(True)

        for direction in ["left", "right", "bottom", "top"]:
            ax.axis[direction].set_visible(False)

        x = np.linspace(-1.0, 1.0, 1000)
        y = np.linspace(-1.0, 1.0, 1000)
        X, Y = np.meshgrid(x, y)
        F = (((abs(X) ** p + abs(Y) ** p) ** (1.0 / p)) - 1)
        ax.contour(X, Y, F, [0])
        plt.savefig('UnitCircle.pdf', facecolor='w', edgecolor='w',
                    papertype=None, format='pdf', transparent=False,
                    bbox_inches='tight', pad_inches=0.1)
        plt.show()
Exemplo n.º 21
0
 def plot_subpaving(self):
     fig = plt.figure(1)
     ax = SubplotZero(fig, 111)
     fig.add_subplot(ax)
     for el in self.outside:
         self.plot_box(X=el, index=0, this_color='red', canvas=ax)
     for el in self.boundary:
         self.plot_box(X=el, index=0, this_color='yellow', canvas=ax)
     for el in self.inside:
         self.plot_box(X=el, index=0, this_color='green', canvas=ax)
     ax.set_xlim(-12., 12.)
     ax.set_ylim(-12., 12.)
     ax.axis('equal')
     plt.show()
     return
Exemplo n.º 22
0
def setup_two_axes(fig, labelpad=1, invisible=["bottom", "top", "right"]):
    plt.rcParams['xtick.major.pad'] = 0.1
    plt.rcParams['xtick.minor.pad'] = 0.1
    plt.rcParams['ytick.major.pad'] = 2
    plt.rcParams['ytick.minor.pad'] = 2
    ax = SubplotZero(fig, 1, 1, 1)
    ax.yaxis.labelpad = labelpad
    fig.add_subplot(ax)
    # make xzero axis (horizontal axis line through y=0) visible.
    ax.axis["xzero"].set_visible(True)
    ax.xaxis.labelpad = labelpad    
    # make other axis (bottom, top, right) invisible.
    for n in invisible:
        ax.axis[n].set_visible(False)
    return ax
Exemplo n.º 23
0
    def run(self, results):
        par1 = self.getValueOfParameter("parameter 1")
        par2 = self.getValueOfParameter("parameter 2")
        i = int(self.getValueOfParameter("iteration number"))
        title = self.getValueOfParameter("title")
        
        if(par1==""):
            return False
        
        if(par2==""):
            return False
        
        if(i >= results.__len__()):
            return False
        
        
        dialogform = Dialog(QApplication.activeWindow())
        fig = Figure((5.0, 4.0), dpi=100)
        ax = SubplotZero(fig, 1, 1, 1)
        fig.add_subplot(ax)

        for n in ["top", "right"]:
            ax.axis[n].set_visible(False)
            
        for n in ["bottom", "left"]:
            ax.axis[n].set_visible(True)
        
        y1 = results[i].getResults(par1)
        y2 = results[i].getResults(par2)    
        
        if(not(y1.__len__())):
            return False
        
        if(not(y2.__len__())):
            return False
        
        ax.plot(range(0,y1.__len__()),y1,color='r')
        ax.plot(range(0,y2.__len__()),y2,color='b')
        ax.set_title(title)
        
        leg = ax.legend((par1, par2),
           'upper center', shadow=True)
        
        frame  = leg.get_frame()
        frame.set_facecolor('0.80')    # set the frame face color to light gray
        
        # matplotlib.text.Text instances
        for t in leg.get_texts():
            t.set_fontsize('small')    # the legend text fontsize
        
        # matplotlib.lines.Line2D instances
        for l in leg.get_lines():
            l.set_linewidth(1.5)  # the legend line width
        
        dialogform.showFigure(fig)
        return True
Exemplo n.º 24
0
def test_min_max_plane_indices(obj_img, Nx, Ny, dx, dy, Nt, Nr, dr):

    bx = -Nx / 2 * dx
    by = -Ny / 2 * dy
    fovx = Nx * dx
    fovy = Ny * dy
    r = np.ceil(np.sqrt((fovx)**2 + (fovy)**2))
    xc = dx / 2
    yc = -dy / 2
    sdd = 2 * r

    p1x = np.zeros(Nt, dtype=TYPE)
    p1y = np.zeros(Nt, dtype=TYPE)
    p2x = np.zeros(Nt, dtype=TYPE)
    p2y = np.zeros(Nt, dtype=TYPE)
    for angle in np.arange(Nt):
        text = ''
        legend_list = []
        fig = plt.figure(figsize=(8, 8))
        ax = SubplotZero(fig, 111)
        fig.add_subplot(ax)
        plt.imshow(obj_img, cmap=plt.cm.gray, interpolation='none', \
                            extent=[bx,-bx, by, -by], alpha=0.5)
        for t in np.arange(-Nr / 2, Nr / 2):
            # find p1-detector and p2-source coordinates
            p1x[angle], p1y[angle] = get_p1(angle * np.pi / Nt, t, r, xc, yc,
                                            dr)
            p2x[angle], p2y[angle] = get_p2(angle*np.pi/Nt, sdd, p1x[angle], \
                                            p1y[angle])
            plt.plot( [p1x[angle], p2x[angle]] ,[p1y[angle], p2y[angle]], ':',\
                      linewidth = 3 )
            imin, imax, jmin, jmax = min_max_plane_indices(Nx, Ny, \
                p1x[angle], p1y[angle], p2x[angle], p2y[angle], bx, by, dx, dy)
            text += '(t=' + str(t) + ') imin:' + str(imin) + ', imax:' + \
                    str(imax) + ' ,jmin:' + str(jmin) + ' ,jmax:' + \
                    str(jmax) + '\n'
            legend_list.append('(t=' + str(t) + ')')
        for direction in ["xzero", "yzero"]:
            ax.axis[direction].set_axisline_style("-|>")
            ax.axis[direction].set_visible(True)
        ax.xaxis.set_ticks(np.arange(-Nx, Nx, 2))
        ax.yaxis.set_ticks(np.arange(-Ny, Ny, 2))
        plt.axis('equal')
        plt.grid(True)
        plt.legend(legend_list)
        plt.title(text, fontsize=10)
Exemplo n.º 25
0
def open_window_and_show_results(points, curve, bezier_points):

    # Generate the curve
    curve_begin = min(points, key=lambda p: p.x)
    curve_end = max(points, key=lambda p: p.x)

    curve_begin = floor(curve_begin.x)
    curve_end = ceil(curve_end.x)

    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    curve_points = []

    if (len(curve) == 3):
        curve_points = generate_curve_points_quadratic(
            [x * 0.1 for x in range(curve_begin * 10, curve_end * 10)],
            curve[0], curve[1], curve[2])  # values for x²
    elif (len(curve) == 4):
        curve_points = generate_curve_points_cubic(
            [x * 0.1 for x in range(curve_begin * 10, curve_end * 10)],
            curve[0], curve[1], curve[2], curve[3])  # values for x²
    else:
        raise "Length of curve has to be 3 or 4"

    # plot_points(plt, curve_points, 'blue')

    # plot_points(plt, points, 'ro')
    plot_points(plt, points, 'red')

    plot_points(plt, bezier_points, 'go')

    plot_points(
        plt,
        draw_bezier_curve(bezier_points[0], bezier_points[1], bezier_points[2],
                          bezier_points[3]), 'orange')

    plt.show()
Exemplo n.º 26
0
def plot_points_helper(x, y, x_poly, y_poly, scale_plot=True):

    figure = plt.figure(figsize=(12, 8))
    ax = SubplotZero(figure, 111)
    figure.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    scale = np.mean(x[x > 0]) + np.mean(y[y > 0]) if scale_plot else 0
    plt.xlim([min(x) - scale, max(x) + scale])
    plt.ylim([min(y) - scale, max(y) + scale])

    plt.scatter(x, y)
    plt.plot(x_poly, y_poly, color='r')
    plt.show()
Exemplo n.º 27
0
def initplot(size):
    """
    Inicializa o desenho de gráficos.
    """
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
    ax.set_xlim(-10, size)
    ax.set_ylim(-10, size)

    return (fig, ax)
Exemplo n.º 28
0
def _blank_plot(domain, ran):
    # make the plot
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    # thicken the axis lines
    ax.axhline(linewidth=1.7, color="k")
    ax.axvline(linewidth=1.7, color="k")

    x_lower, x_upper = int(domain.left), int(domain.right)  # needs to be changed, is just a temporary type changer
    y_lower, y_upper = int(ran.left), int(ran.right)

    # remove tick lines on the axes
    plt.xticks([])
    plt.yticks([])
    plt.ylim(y_lower, y_upper)
    plt.xlim(x_lower, x_upper)

    # add axes labels
    ax.text(1.05, 0, r'$x$', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')
    ax.text(0, 1.05, r'$y$', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')

    # end-of-axis arrows
    x_width = (abs(plt.xlim()[0]) + abs(plt.xlim()[1]))
    y_width = (abs(plt.ylim()[0]) + abs(plt.ylim()[1]))
    plt.arrow(plt.xlim()[1], -0.003, 0.00000000001, 0,
              width=x_width*0.0015*0.5, color="k", clip_on=False,
              head_width=y_width*0.12/7, head_length=x_width*0.024*0.5)
    plt.arrow(0.003, plt.ylim()[1], 0, 0.00000000001,
              width=y_width*0.0015*0.5, color="k", clip_on=False,
              head_width=x_width*0.12/7, head_length=y_width*0.024*0.5)

    # only show cartesian axes
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)
Exemplo n.º 29
0
    def create_plot(self, scale, y_bounds, points=None, file_name=None):
        """
        Using matplotlib, graphs the given points on a Cartesian plane.

        Adapted from the matplotlib documentation:
        https://matplotlib.org/examples/axes_grid/demo_axisline_style.html.

        args:
            scale: Numpy array of increments for the x-axis.
            points: Numpy array of points' Y-values to be plotted.
            y_bounds: integer determining scale of y axis
            file_name: name for plot to be serialized under.
        """

        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt

        fig = plt.figure(1)
        subplot = SubplotZero(fig, 111)
        fig.add_subplot(subplot)

        for direction in ['xzero', 'yzero']:
            subplot.axis[direction].set_axisline_style('-|>')
            subplot.axis[direction].set_visible(True)

        for direction in ['left', 'right', 'bottom', 'top']:
            subplot.axis[direction].set_visible(False)

        subplot.set_ylim([-y_bounds, y_bounds])

        if points is not None:
            subplot.plot(scale, points)

        if file_name:
            plt.savefig(file_name)
        else:
            plt.show()
Exemplo n.º 30
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero
import numpy as np

fig = plt.figure(1, (4,3))

# a subplot with two additiona axis, "xzero" and "yzero". "xzero" is
# y=0 line, and "yzero" is x=0 line.
ax = SubplotZero(fig, 1, 1, 1)
fig.add_subplot(ax)

# make xzero axis (horizontal axis line through y=0) visible.
ax.axis["xzero"].set_visible(True)
ax.axis["xzero"].label.set_text("Axis Zero")

# make other axis (bottom, top, right) invisible.
for n in ["bottom", "top", "right"]:
    ax.axis[n].set_visible(False)

xx = np.arange(0, 2*np.pi, 0.01)
ax.plot(xx, np.sin(xx))

plt.show()

Exemplo n.º 31
0
##Input : the stress tensor
##Output : anmiation

# ########################
# INPUT : Stress tensor ! must be a plan stress state !
# ########################
Sigma = np.array([[400, 100, 0], [100, -200, 0], [0, 0, 0]], float)
print("Sigma=", Sigma)

# ########################
# Set up the figure, the axis, and the plot element we want to animate
# ########################
fig = plt.figure(1)
Sig_max = 500.0
# Espace x,y
ax1 = SubplotZero(fig, 121)
fig.add_subplot(ax1)
#
for direction in ["xzero", "yzero"]:
    ax1.axis[direction].set_axisline_style("-|>")
    ax1.axis[direction].set_visible(True)
#
for direction in ["left", "right", "bottom", "top"]:
    ax1.axis[direction].set_visible(False)

ax1.set_aspect('equal')

ax1.set_xlim(-Sig_max, Sig_max)
ax1.set_ylim(-Sig_max, Sig_max)
ax1.text(0.,
         1.05,
Exemplo n.º 32
0
#!/usr/bin/env python3

from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.transforms import BlendedGenericTransform
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np


if __name__ == '__main__':

    fig = plt.figure(1)
    ax = SubplotZero(fig, 1, 1, 1)
    # fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')

    fig.add_subplot(ax)



    ax.text(-1.15, 0.99, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1., -0.25, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')
    #
    for direction in ["xzero", "left"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = np.linspace(-1., +1., 1000) # x < 0
    # print(x)
Exemplo n.º 33
0
def visualize_test_between_class(test, human, non_human):
    fig = plt.figure("Trajectories for Test, Human, and Non-Human")
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    line_style = ['r.-', 'gx-', 'bo-']

    # plotting test data
    x = [i.pose.position.x for i in test]
    y = [i.pose.position.y for i in test]
    ax.plot(x, y, line_style[0], label="Test")
    # plotting human data
    x = [i.pose.position.x for i in human]
    y = [i.pose.position.y for i in human]
    ax.plot(x, y, line_style[1], label="Human")
    # plotting non-human data
    x = [i.pose.position.x for i in non_human]
    y = [i.pose.position.y for i in non_human]
    ax.plot(x, y, line_style[2], label="Non-human")

    ax.margins(0.05)
    ax.legend(loc="lower right", fontsize=10)
    plt.title("Chunks of Trajectories")
    plt.xlabel("Axis")
    plt.ylabel("Ordinate")

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    pylab.grid()
    plt.show()
    def renderGraph(self): # pylint: disable=R0914
        assert len(self._oData.aoSeries) == 1;
        oSeries = self._oData.aoSeries[0];

        # hacking
        #self.setWidth(512);
        #self.setHeight(128);
        # end

        oFigure = self._createFigure();
        from mpl_toolkits.axes_grid.axislines import SubplotZero;
        oAxis = SubplotZero(oFigure, 111);
        oFigure.add_subplot(oAxis);

        # Disable all the normal axis.
        oAxis.axis['right'].set_visible(False)
        oAxis.axis['top'].set_visible(False)
        oAxis.axis['bottom'].set_visible(False)
        oAxis.axis['left'].set_visible(False)

        # Use the zero axis instead.
        oAxis.axis['yzero'].set_axisline_style('-|>');
        oAxis.axis['yzero'].set_visible(True);
        oAxis.axis['xzero'].set_axisline_style('-|>');
        oAxis.axis['xzero'].set_visible(True);

        if oSeries.aoYValues[-1] == 100:
            sColor = 'green';
        elif oSeries.aoYValues[-1] > 75:
            sColor = 'yellow';
        else:
            sColor = 'red';
        oAxis.plot(oSeries.aoXValues, oSeries.aoYValues, '.-', color = sColor, linewidth = 3);
        oAxis.fill_between(oSeries.aoXValues, oSeries.aoYValues, facecolor = sColor, alpha = 0.5)

        oAxis.set_xlim(left = -0.01);
        oAxis.set_xticklabels([]);
        oAxis.set_xmargin(1);

        oAxis.set_ylim(bottom = 0, top = 100);
        oAxis.set_yticks([0, 50, 100]);
        oAxis.set_ylabel('%');
        #oAxis.set_yticklabels([]);
        oAxis.set_yticklabels(['', '%', '']);

        return self._produceSvg(oFigure, False);
Exemplo n.º 35
0
    def renderGraph(self):  # pylint: disable=R0914
        assert len(self._oData.aoSeries) == 1
        oSeries = self._oData.aoSeries[0]

        # hacking
        # self.setWidth(512);
        # self.setHeight(128);
        # end

        oFigure = self._createFigure()
        from mpl_toolkits.axes_grid.axislines import SubplotZero

        # pylint: disable=E0401
        oAxis = SubplotZero(oFigure, 111)
        oFigure.add_subplot(oAxis)

        # Disable all the normal axis.
        oAxis.axis["right"].set_visible(False)
        oAxis.axis["top"].set_visible(False)
        oAxis.axis["bottom"].set_visible(False)
        oAxis.axis["left"].set_visible(False)

        # Use the zero axis instead.
        oAxis.axis["yzero"].set_axisline_style("-|>")
        oAxis.axis["yzero"].set_visible(True)
        oAxis.axis["xzero"].set_axisline_style("-|>")
        oAxis.axis["xzero"].set_visible(True)

        if oSeries.aoYValues[-1] == 100:
            sColor = "green"
        elif oSeries.aoYValues[-1] > 75:
            sColor = "yellow"
        else:
            sColor = "red"
        oAxis.plot(oSeries.aoXValues, oSeries.aoYValues, ".-", color=sColor, linewidth=3)
        oAxis.fill_between(oSeries.aoXValues, oSeries.aoYValues, facecolor=sColor, alpha=0.5)

        oAxis.set_xlim(left=-0.01)
        oAxis.set_xticklabels([])
        oAxis.set_xmargin(1)

        oAxis.set_ylim(bottom=0, top=100)
        oAxis.set_yticks([0, 50, 100])
        oAxis.set_ylabel("%")
        # oAxis.set_yticklabels([]);
        oAxis.set_yticklabels(["", "%", ""])

        return self._produceSvg(oFigure, False)
Exemplo n.º 36
0
from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np

filename = 'data/plot_exp1_1280.txt'
pair_list = [line.split() for line in open(filename)]
p = [float(pair[0]) for pair in pair_list]
probability = [float(pair[1]) for pair in pair_list]

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

	ax.axis['xzero'].set_label('p')
	ax.axis['yzero'].set_label('probability that the path exists')

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    ax.plot(p, probability)

    plt.show()
Exemplo n.º 37
0
from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>, size=2")
    ax.axis[direction].set_visible(True)
    ax.set_yticklabels([])
    ax.set_xticklabels([])

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)
ax.axis['xzero'].set_label('asdfsadf')
x = np.linspace(-10, 10, 1000)
ax.plot(x, np.sin(x*np.pi))

plt.show()
Exemplo n.º 38
0
    def renderGraph(self):  # pylint: disable=R0914
        assert len(self._oData.aoSeries) == 1
        oSeries = self._oData.aoSeries[0]

        # hacking
        #self.setWidth(512);
        #self.setHeight(128);
        # end

        oFigure = self._createFigure()
        from mpl_toolkits.axes_grid.axislines import SubplotZero
        # pylint: disable=E0401
        oAxis = SubplotZero(oFigure, 111)
        oFigure.add_subplot(oAxis)

        # Disable all the normal axis.
        oAxis.axis['right'].set_visible(False)
        oAxis.axis['top'].set_visible(False)
        oAxis.axis['bottom'].set_visible(False)
        oAxis.axis['left'].set_visible(False)

        # Use the zero axis instead.
        oAxis.axis['yzero'].set_axisline_style('-|>')
        oAxis.axis['yzero'].set_visible(True)
        oAxis.axis['xzero'].set_axisline_style('-|>')
        oAxis.axis['xzero'].set_visible(True)

        if oSeries.aoYValues[-1] == 100:
            sColor = 'green'
        elif oSeries.aoYValues[-1] > 75:
            sColor = 'yellow'
        else:
            sColor = 'red'
        oAxis.plot(oSeries.aoXValues,
                   oSeries.aoYValues,
                   '.-',
                   color=sColor,
                   linewidth=3)
        oAxis.fill_between(oSeries.aoXValues,
                           oSeries.aoYValues,
                           facecolor=sColor,
                           alpha=0.5)

        oAxis.set_xlim(left=-0.01)
        oAxis.set_xticklabels([])
        oAxis.set_xmargin(1)

        oAxis.set_ylim(bottom=0, top=100)
        oAxis.set_yticks([0, 50, 100])
        oAxis.set_ylabel('%')
        #oAxis.set_yticklabels([]);
        oAxis.set_yticklabels(['', '%', ''])

        return self._produceSvg(oFigure, False)
Exemplo n.º 39
0
                horizontalalignment='center',
                verticalalignment='center',
                fontsize=16, fontweight='demibold',
                transform=ax.transAxes)

        plotting.remove_axis_junk(ax)
        t = np.arange(p_net.shape[1])*PSET.dt*PSET.decimate_q
        inds = (t >= T[0]) & (t <= T[1])
        ax.plot(t[inds], p_net[i, inds], 'k', lw=1)
        ax.set_ylabel(ylabel)
        ax.set_xticklabels([])
        


    # panel F. Illustration of 4-sphere volume conductor model geometry
    ax = SubplotZero(fig, gs[2, 1])
    fig.add_subplot(ax)
    ax.set_title('four-sphere volume conductor model')

    for direction in ["xzero"]:
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    
    theta = np.linspace(0, np.pi, 31)
    
    # draw some circles:
    for i, r, label in zip(range(4), PSET.foursphereParams['radii'], ['brain', 'CSF', 'skull', 'scalp']):
        ax.plot(np.cos(theta)*r, np.sin(theta)*r, 'C{}'.format(i), label=label + r', $r_%i=%i$ mm' % (i+1, r / 1000), clip_on=False)
Exemplo n.º 40
0
ax0.axis('off')
ax0.set_title('extracellular potential')
ax1 = fig.add_subplot(gs[:6, 1], aspect='equal')  # dipole moment ill.
ax1.axis('off')
ax1.set_title('extracellular potential')
ax2 = fig.add_subplot(gs[:6, 2], aspect='equal')  # dipole moment ill.
ax2.axis('off')
ax2.set_title('magnetic field')
# ax3 = fig.add_subplot(gs[0, 3], aspect='equal')             # spherical shell model ill.
# ax3.set_title('4-sphere volume conductor')
# ax4 = fig.add_subplot(gs[1, 3],
# aspect='equal'
# )                 # MEG/EEG forward model ill.
# ax4.set_title('EEG and MEG signal detection')

ax3 = SubplotZero(fig, gs[7:, 0])
fig.add_subplot(ax3)
ax3.set_title('4-sphere volume conductor', verticalalignment='bottom')
ax4 = fig.add_subplot(gs[7:, 1])  # EEG
ax4.set_title('scalp electric potential $\phi_\mathbf{p}(\mathbf{r})$')
ax5 = fig.add_subplot(gs[7:, 2], sharey=ax4)  # MEG
# ax5.set_title('scalp magnetic field')

#morphology - line sources for panels A and B
zips = []
xz = cell.get_idx_polygons()
for x, z in xz:
    zips.append(zip(x, z))
for ax in [ax0]:
    polycol = PolyCollection(zips,
                             linewidths=(0.5),
Exemplo n.º 41
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero
import numpy as np

fig = plt.figure(1, (4, 3))

# a subplot with two additiona axis, "xzero" and "yzero". "xzero" is
# y=0 line, and "yzero" is x=0 line.
ax = SubplotZero(fig, 1, 1, 1)
fig.add_subplot(ax)

# make xzero axis (horizontal axis line through y=0) visible.
ax.axis["xzero"].set_visible(True)
ax.axis["xzero"].label.set_text("Axis Zero")

# make other axis (bottom, top, right) invisible.
for n in ["bottom", "top", "right"]:
    ax.axis[n].set_visible(False)

xx = np.arange(0, 2 * np.pi, 0.01)
ax.plot(xx, np.sin(xx))

plt.show()
Exemplo n.º 42
0
        cur_x0 = cur_x0 + (cur_a1 - cur_x0) / (i + 2)
        cur_x1 = cur_x1 + (cur_a0 - cur_x1) / (i + 2)

    return x0s, x1s


def ficthist(t):
    x0_last = []
    for i in range(t):
        x0s, x1s = fict(t)
        x0_last.append(x0s[-1])
    return x0_last


x0s, x1s = fict(t)

fig, ax = plt.subplots()
ax.plot(x0s, 'r-')
ax.plot(x1s, 'b-')
#plt.savefig('fictitious.png')
#plt.savefig('fictitious.pdf')
plt.show()

fig = plt.figure()
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
ax.hist(ficthist(t))
#plt.savefig('fictitious_hist.png')
#plt.savefig('fictitious_hist.pdf')
plt.show()
Exemplo n.º 43
0
#klasyfikator
def classifier(x):
    if g1(x) > g2(x):
        return 1
    else:
        return 2


N = 10

x1 = 4 * np.random.randn(N, 2) + (-2)
x2 = 4 * np.random.randn(N, 2) + (+2)

fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>")
    ax.axis[direction].set_visible(True)

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)

ax.plot(x1[:, 0], x1[:, 1], 'yo', x2[:, 0], x2[:, 1], 'go')
ax.plot([-10, 10], [-10, 10])

data = np.vstack((x1, x2))
print(data)
# #wartości funkcji klasyfikujących
# y1=[g1(data[i,:]) for i in range(2*N)]
Exemplo n.º 44
0
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero
import numpy as np
import fractions
# 改変箇所をまとめておく
FIGNUM = 1 # 0 or 1
if FIGNUM == 0:
    t_max, step = 2, fractions.Fraction(1,3) # 傾きの最大、最小値の設定
    # 傾きをいくつ刻みで変化させるか。分数のまま計算させるためにFraction()を利用した
if FIGNUM == 1:
    t_max, step = 3, fractions.Fraction(1,2)
x_max = 7
y_max = 6
y_min = -5

def f(x, t):
	return t*x-t**2
# 以上が改変箇所

t_min = -t_max  # 対称性の利用
x_min = -x_max
if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)
    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
    for direction in ["left", "right", "bottom", "top"]:
Exemplo n.º 45
0
    p_delta_x = (b-a)/(pixel_h-20) #ancho del pixel
    p_delta_y = (y_max-y_min)/(pixel_v-20) #largo del pixel
    px = np.zeros(len(x_real))
    py = np.zeros(len(y_real))
    #Cómputo de las coordenadas en pantalla 
    for i in range(len(x_real)):
        px[i] = (x_real[i]/p_delta_x)+10
    for j in range(len(y)):
        py[j]= ((y_max-y[j])/p_delta_y)+10
    return px, py

z = coor_screen(x,y)

#Para proyectar figura
fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

for direccion in ["xzero", "yzero"]:
    ax.axis[direccion].set_axisline_style("-|>")
    ax.axis[direccion].set_visible(True)

for direccion in ["left", "right", "bottom", "top"]:
    ax.axis[direccion].set_visible(False)

ax.plot(z[0], z[1]-250) #Restamos 250 porque interpreta el origen del eje x en la parte superior de la pantalla
#TENER EN CUENTA QUE LOS LABELS EN LOS EJES SON LAS COORDENADAS EN PANTALLA
#∫∫∫∫∫∫∫∫savefig("grafica.png", dpi=72)
plt.show()

Exemplo n.º 46
0
from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np

filename = "data/exp2_1000.txt"
input = open(filename)

N = int(input.readline())
pair_list = [line.split() for line in input]
p = [float(pair[0]) / float(N ** 2) for pair in pair_list]
size = [float(pair[1]) for pair in pair_list]

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

        ax.axis["xzero"].set_label("p")
        ax.axis["yzero"].set_label("size of largest component")

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    ax.plot(p, size)

    plt.show()
Exemplo n.º 47
0
ax0.axis('off')
ax0.set_title('extracellular potential')
ax1 = fig.add_subplot(gs[:6, 1], aspect='equal') # dipole moment ill.
ax1.axis('off')
ax1.set_title('extracellular potential')
ax2 = fig.add_subplot(gs[:6, 2], aspect='equal') # dipole moment ill.
ax2.axis('off')
ax2.set_title('magnetic field')
# ax3 = fig.add_subplot(gs[0, 3], aspect='equal')             # spherical shell model ill.
# ax3.set_title('4-sphere volume conductor')
# ax4 = fig.add_subplot(gs[1, 3],
                      # aspect='equal'
                      # )                 # MEG/EEG forward model ill.
# ax4.set_title('EEG and MEG signal detection')

ax3 = SubplotZero(fig, gs[7:, 0])
fig.add_subplot(ax3)
ax3.set_title('4-sphere volume conductor', verticalalignment='bottom')
ax4 = fig.add_subplot(gs[7:, 1]) # EEG
ax4.set_title('scalp electric potential $\phi_\mathbf{p}(\mathbf{r})$')
ax5 = fig.add_subplot(gs[7:, 2], sharey=ax4) # MEG
# ax5.set_title('scalp magnetic field')

#morphology - line sources for panels A and B
zips = []
xz = cell.get_idx_polygons()
for x, z in xz:
    zips.append(zip(x, z))
for ax in [ax0]:
    polycol = PolyCollection(zips,
                             linewidths=(0.5),
Exemplo n.º 48
0
def main():
    f = open("game_output.txt", "r")
    l = json.load(f)
    min_time = 0
    for val in l:
        if min_time == 0:
            min_time = val["time"]
        if val["time"] < min_time:
            min_time = val["time"]
    max_time = 0
    for val in l:
        if max_time == 0:
            max_time = val["time"]
        if val["time"] > max_time:
            max_time = val["time"]

    print "%s %s" % (min_time, max_time)

    fig = plt.figure(1)
    fig.subplots_adjust(right=0.85)
    ax = SubplotZero(fig, 1, 1, 1)
    fig.add_subplot(ax)

    # make right and top axis invisible
    ax.axis["right"].set_visible(False)
    ax.axis["top"].set_visible(False)

    # make xzero axis (horizontal axis line through y=0) visible.
    ax.axis["xzero"].set_visible(False)
    #ax.axis["xzero"].label.set_text("Axis Zero")

    ax.set_xlim(min_time, max_time)
    ax.set_ylim(0, 4)
    ax.set_xlabel("Time")
    ax.set_ylabel("HRV")

    # make new (right-side) yaxis, but wth some offset
    # offset = (20, 0)
    # new_axisline = ax.get_grid_helper().new_fixed_axis

    # ax.axis["right2"] = new_axisline(loc="right",
    #                                  offset=offset,
    #                                  axes=ax)
    # ax.axis["right2"].label.set_text("Label Y2")

    #ax.plot([-2,3,2])
    t_hrv = []
    hrv = []
    for val in l:
        if "hrv" in val.keys():
            t_hrv.append(val["time"])
            hrv.append(val["hrv"])
            #ax.plot(val["time"], val["hrv"], 'b,')
        elif "key" in val.keys():
            ax.plot(val["time"], 2.0, 'r,')
    ax.plot(t_hrv, hrv, 'b-')

    hrv_dict = []
    for el in l:
        try:
            hrv_dict.append((el["time"], el["hrv"]))
        except KeyError:
            pass

    peak_dict = []

    current_peak = 0
    hrv_window = deque()
    hrv_limit = 20
    hrv_total = []
    stop_counter = 0
    hrv_itr = hrv_dict.__iter__()
    b = hrv_itr.next()

    while 1:
        a = [b[0], b[1], 0]
        hrv_window.append(a)
        hrv_total.append(a)
        if len(hrv_window) > hrv_limit:
            hrv_window.popleft()
        max_hrv = 0
        max_time = 0
        for h in hrv_window:
            if h[1] > max_hrv:
                max_time = h[0]
                max_hrv = h[1]
        for h in hrv_window:
            if h[0] == max_time:
                h[2] = h[2] + 1
                break
        try:
            c = hrv_itr.next()
            b = c
        except StopIteration:
            stop_counter = stop_counter + 1
            if stop_counter == hrv_limit:
                break
            
    pulse = 0
    for (time, hrv, score) in hrv_total:
        if score > 17:
            pulse = pulse + 1
            ax.plot(time, hrv, 'g,')

    print "Pulse: %s" % (pulse)
        
    plt.draw()
    plt.show()
Exemplo n.º 49
0
    def visualize_test_between_class(self, test, human, non_human):
        fig = plt.figure("Trajectories for Test, Human, and Non-Human")
        ax = SubplotZero(fig, 111)
        fig.add_subplot(ax)
        line_style = ['r.-', 'gx-', 'bo-']

        # plotting test data
        x = [i.pose.position.x for i in test]
        y = [i.pose.position.y for i in test]
        ax.plot(x, y, line_style[0], label="Test")
        # plotting human data
        x = [i.pose.position.x for i in human]
        y = [i.pose.position.y for i in human]
        ax.plot(x, y, line_style[1], label="Human")
        # plotting non-human data
        x = [i.pose.position.x for i in non_human]
        y = [i.pose.position.y for i in non_human]
        ax.plot(x, y, line_style[2], label="Non-human")

        ax.margins(0.05)
        ax.legend(loc="lower right", fontsize=10)
        plt.title("Chunks of Trajectories")
        plt.xlabel("Axis")
        plt.ylabel("Ordinate")

        for direction in ["xzero", "yzero"]:
            ax.axis[direction].set_axisline_style("-|>")
            ax.axis[direction].set_visible(True)

        for direction in ["left", "right", "bottom", "top"]:
            ax.axis[direction].set_visible(False)

        pylab.grid()
        plt.show()
Exemplo n.º 50
0
# ########################
Sigma=np.array([[S11,S12,S13],[S12,S22, S23 ],[S13,S23, S33 ]],float)
print("Sigma=", Sigma)
VP=np.linalg.eigvals(Sigma)
Sig_max= np.max((VP)) + 5
Sig_min= np.min((VP)) - 5 


# ########################
# Set up the figure, the axis, and the plot element we want to animate
# ########################
fig = plt.figure(1)

# Espace x,y
# Espace Snn,Snt
ax2 = SubplotZero(fig, 111)
fig.add_subplot(ax2)
#
for direction in ["xzero", "yzero"]:
    ax2.axis[direction].set_axisline_style("-|>")
    ax2.axis[direction].set_visible(True)
#
for direction in ["left", "right", "bottom", "top"]:
    ax2.axis[direction].set_visible(False)
    
ax2.set_aspect('equal')

ax2.set_xlim(Sig_min, Sig_max)
ax2.set_ylim(-(Sig_max-Sig_min)/2, (Sig_max-Sig_min)/2)
ax2.text(0., 1.05, '$\sigma_{nt}$',size=20, transform=BlendedGenericTransform(ax2.transData, ax2.transAxes))
ax2.text(1.05, -0.15, '$\sigma_{nn}$',size=20, transform=BlendedGenericTransform(ax2.transAxes, ax2.transData))
Exemplo n.º 51
0
Arquivo: ex_3.py Projeto: NelleV/MGRPR
from classification import linear_regression
from utils import load_data

verbose = True
max_iter = 500

X, Y = load_data('classificationA.train')

beta, u = linear_regression(X, Y)

# Let's plot the result
fig = plt.figure(1)
colors = ['#4EACC5', '#FF9C34', '#4E9A06']
my_members = Y == 0
my_members.shape = (my_members.shape[0])
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>")
    ax.axis[direction].set_visible(True)

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)


ax.plot(X[my_members, 0], X[my_members, 1],
        'w', markerfacecolor=colors[0], marker = '.')

my_members = Y == 1
my_members.shape = (my_members.shape[0])
#!/usr/bin/python
print "content-type: text/html\n"
import cgi,cgitb
cgitb.enable()


from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = np.linspace(-0.5, 1., 100)
    ax.plot(x, np.sin(x*np.pi))

    plt.show()
Exemplo n.º 53
0
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero
if 1:
    fig = plt.figure(1)
    fig.subplots_adjust(right=0.85)
    ax = SubplotZero(fig, 1, 1, 1)
    fig.add_subplot(ax)
    ax.axis["right"].set_visible(False)
    ax.axis["top"].set_visible(False)
    ax.axis["xzero"].set_visible(True)
    ax.axis["xzero"].label.set_text("Axis Zero")
    ax.set_ylim(-2, 4)
    ax.set_xlabel("Label X")
    ax.set_ylabel("Label Y")
    offset = (20, 0)
    new_axisline = ax.get_grid_helper().new_fixed_axis
    ax.axis["right2"] = new_axisline(loc="right",
                                     offset=offset,
                                     axes=ax)
    ax.axis["right2"].label.set_text("Label Y2")
    ax.plot([-2,3,2])
    plt.draw()
    plt.show()
Exemplo n.º 54
0
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid.axislines import SubplotZero


# 図の背景の諸体裁を設定

# 作図スペースを用意(?)。個々のコードの意味がわかりません。	
fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

# 軸の設定
ax.axhline(linewidth=1.2, color="black")
ax.axvline(linewidth=1.2, color="black")

# 軸に矢印
for direction in ["xzero", "yzero"]:
	ax.axis[direction].set_axisline_style("-|>")
	ax.axis[direction].set_visible(True)

# 四方のaxis(?)、spine(?)を消す	
for direction in ["left", "right", "bottom", "top"]:
	ax.axis[direction].set_visible(False)

# 軸に名前を付ける。位置は適宜設定。	
plt.figtext(0.93, 0.37, 'x')  
plt.figtext(0.505, 0.95, 'y')
Exemplo n.º 55
0
def f(x, a):
    return a*x-x**2  # 包絡線の式を入れる
p = -3  # xの最小値
q = 3  # xの最大値
n = 12  # 引く包絡線の数
a_min = -10  # 表示させるaの最小値
a_max = 10  # 表示させるaの最大値
y_min = -6  # 表示させるbの最小値(最大値はa軸とb軸の縮尺が1:1になるよう自動で決まる)
# アスペクト比を定めただけだと異常に縦長なグラフが出てくるのでylimを定めた
y_max = y_min+a_max-a_min  # これは変数ではない
plt.figtext(0.85, 0.35, '$a$')  # 直接位置を指定しているので、グラフの位置を変えるときにこれも変える
plt.figtext(0.5, 0.95, '$b$')
# ここより上に変数が入る
fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
ax.axhline(linewidth=1.0, color="black")
ax.axvline(linewidth=1.0, color="black")
ax.set_xticks([])  # 空のlistを指定することでticksが入らない
ax.set_yticks([])
ax.set(aspect=1)
for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>")
    ax.axis[direction].set_visible(True)
plt.ylim(ymin=y_min)  # この位置より前に置くとx方向が狭くなってしまった
plt.ylim(ymax=y_max)
a = linspace(a_min, a_max, (a_max-a_min) * 10)  # 点の数はaの動く範囲の長さ×10,これで曲線にも対応する
# linspaceの点の数に小数が来ることがあり得るのですが、その場合は勝手に小数点以下を切り捨てた数の点をとってくれるようです
for i in range(n):
    r = p+(q-p)*i/(n-1)  # n個の接線を引き2個は両端にあるので区間はn-1等分される
"""
Copyright (c) 2012 Michael Markieta
See the file license.txt for copying permission.
"""
from polar_grid import polar_grid
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero

# Setup plotting for our polar grid
fig = plt.figure(1, figsize=(7,7))
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

# add axis lines for coordinate geometry (4 quadrants)
for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>", size=.75)
    ax.axis[direction].set_visible(True)

# remove axis lines/labels for rectangular geometry (-x and -y don't exist)
for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)

X = [] # hold x-coordinates from radial dividers
Y = [] # hold y-coordinates from radial dividers

# Generate geometry for a polar grid of 4-unit radius, centroid at (-2,1), with 8 divisions and precision of 4000 points
geom = polar_grid(rho=4, centroid=(-2,1), theta=8, tau=4000)

# Add coordinates from each radial divider to the X and Y lists
for num in range(0, len(geom)):
    for (x,y) in geom[num][1]:
Exemplo n.º 57
0
        cur_x0 = cur_x0 + (cur_a1 - cur_x0)/(i + 2)
        cur_x1 = cur_x1 + (cur_a0 - cur_x1)/(i + 2)

    return x0s, x1s

def ficthist(t):
    x0_last = []
    for i in range(t):
        x0s, x1s = fict(t)
        x0_last.append(x0s[-1])
    return x0_last

x0s, x1s = fict(t)

fig, ax = plt.subplots()
ax.plot(x0s, 'r-')
ax.plot(x1s, 'b-')
#plt.savefig('fictitious.png')
#plt.savefig('fictitious.pdf')
plt.show()


fig = plt.figure()
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
ax.hist(ficthist(t))
#plt.savefig('fictitious_hist.png')
#plt.savefig('fictitious_hist.pdf')
plt.show()

Exemplo n.º 58
0
def main(path, name):
  from numpy import linspace, loadtxt
  d = SimulatedData(path) 
  psth = d.spike_time.psth()
  
  from mpl_toolkits.axes_grid.axislines import SubplotZero
  import matplotlib.pyplot as plt
  
  f1 = plt.figure(figsize=[6,8])
  ax = SubplotZero(f1, 411)
  f1.add_subplot(ax)  
  psth.plot_raster(ax)
  
  ax = SubplotZero(f1, 412)
  f1.add_subplot(ax)
  psth.plot_rate(ax, smoothed=True)
  
  ax = SubplotZero(f1, 413)
  f1.add_subplot(ax)
  dat = loadtxt(d.path['ML response'])
  t = linspace(0, 5000, dat.size)
  ax.plot(t, dat, 'k')
  for direction in ["left", "right", "top", "bottom"]:
    ax.axis[direction].set_visible(False)
  logging.info(str(dir(ax.axis["bottom"])))
#  ax.axis["bottom"].major_ticklabels=[]
  ax.set_title("ML")
  
  ax = SubplotZero(f1, 414)
  f1.add_subplot(ax)
  dat = loadtxt(d.path['HHLS response'])
  t = linspace(0, 5000, dat.size)
  ax.plot(t, dat, 'k')
  for direction in ["left", "right", "top"]:
    ax.axis[direction].set_visible(False)
  ax.axis["bottom"].set_label("Time (ms)")
  ax.set_title("HHLS")
  
  f1.subplots_adjust(hspace=0.47, top=0.95, bottom=0.05)
  
  f2 = plt.figure(figsize=[4,4])
  ax = SubplotZero(f2, 111)
  f2.add_subplot(ax)
  mf = psth.hist_mean_rate(ax, bins=linspace(0,8,20))
  ax.set_title({"highvar": "High variance", "lowvar": "Low variance"}[name])
  print "Mean firing rate =", mf.mean(), "Hz", "(", mf.std(),")"
  plt.show()
Exemplo n.º 59
0
#!/bin/env python
from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = np.linspace(-0.5, 1., 100)
    ax.plot(x, np.sin(x * np.pi))

    plt.show()
    plt.savefig("foo.png")
    plt.savefig("foo.eps")
    plt.savefig("foo.pdf")
Exemplo n.º 60
0
acceleration = pol2cart(aforce,adeg)

orig = [0,0]

h = orig + heading # normalized heading
x = orig + orientation # normalized orientation
g = orig + acceleration

print h,x,g

soa = np.array([h,x,g]) # vectors
print soa
X,Y,U,V = zip(*soa) # convert to turples of U and V components

fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
colors = ('r','g','b')
qv = ax.quiver(X,Y,U,V,color=colors,angles='xy',scale_units='xy',scale=1)

labels = ('heading: {} deg'.format(hdeg), 'Orientation, drift: {} deg'.format(drift), '{} g at {} deg'.format(aforce,adeg))
pos = ('N','E','S')
for x,y,l,c,p in zip(U,V,labels,colors,pos):
	plt.quiverkey(qv,x,y,0,l,color=c,coordinates='data',labelpos=p)

ax.set_xlim([-2,2])
ax.set_ylim([-2,2])

# show cartisian axis
# for direction in ["xzero", "yzero"]:
#     ax.axis[direction].set_visible(True)