예제 #1
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
예제 #2
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)
예제 #3
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()
예제 #4
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]
    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)
예제 #6
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()
예제 #7
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()
예제 #8
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)
        
        x = results[i].getResults(par1)
        y = results[i].getResults(par2)    
        
        if(not(x.__len__())):
            return False
        
        if(not(y.__len__())):
            return False
        
        ax.plot(x,y,'.')
        
        #plot middle
        xm = range(math.floor(min(ax.axis())),math.floor(max(ax.axis())+1),1)
        ax.plot(xm,xm)
        ax.set_xlabel(par1)
        ax.set_ylabel(par2)
        ax.set_title(title)
        dialogform.showFigure(fig)
        return True
    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);
    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()
예제 #11
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()
예제 #12
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
예제 #13
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()
예제 #14
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()
예제 #15
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()
예제 #16
0
파일: game.py 프로젝트: qdot/pulse-project
    def draw_graph(self):
        min_time = 0
        max_time = 0
        for val in self.readings:
            if min_time == 0:
                min_time = val["time"]
            if val["time"] < min_time:
                min_time = val["time"]
            if max_time == 0:
                max_time = val["time"]
            if val["time"] > max_time:
                max_time = val["time"]
                
        fig = plt.figure(1)

        fig.subplots_adjust(right=0.85)
        ax = SubplotZero(fig, 1, 1, 1)
        fig.add_subplot(ax)
        plt.title("Score for Game: %s" % self.score)
        # 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.set_xlim(min_time, max_time)
        ax.set_ylim(0, 4)
        ax.set_xlabel("Time")
        ax.set_ylabel("HRV")

        t_hrv = []
        hrv = []
        for val in self.readings:
            if "hrv" in val.keys():
                t_hrv.append(val["time"])
                hrv.append(val["hrv"])
            else:
                ax.plot(val["time"], 2.0, 'r.')

        for peak in self.peaks:
            ax.plot(peak["time"], peak["hrv"], 'g.', markersize=10)
        ax.plot(t_hrv, hrv, 'b-')

        plt.savefig('pulse_graph')
예제 #17
0
from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np
import math

filename = 'data/plot_exp3.txt'
pair_list = [line.split() for line in open(filename)]
log_p = [math.log(float(pair[0])) for pair in pair_list]
log_size = [math.log(float(pair[1])) for pair in pair_list]

print np.polyfit(log_p, log_size, 1)

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('log_n')
	ax.axis['yzero'].set_label('log_s')

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

    ax.plot(log_p, log_size)

    plt.show()
예제 #18
0
    ax.axis[direction].set_visible(False)
ax.axis["yzero"].set_axis_direction("left")
ax.grid(True)
ax.minorticks_on()

ax.contour(x,
           y,
           x**2 + 2. * x * y + y**2 - 8. * x, [0],
           linewidths=1.5,
           colors='r')
ax.text(1.75, -4.5, r'$x^2+2xy+y^2-8x=0$', color='r')
ax.arrow(.5, -1, 0, 5, color='orange', head_width=.1, head_length=.2)
ax.text(.75, 4, r'$\bar{y}$', color='orange')
ax.arrow(-2.5, 1.5, 5.5, 0, color='orange', head_width=.1, head_length=.2)
ax.text(3, 1, r'$\bar{x}$', color='orange')
ax.plot(.5, 1.5, 'ko')
ax.text(.25, 1.75, r'V')

ax.arrow(-4.5, -4.5, 9, 9, color='m', ls='dashed', lw=.5), ax.text(-4,
                                                                   -4,
                                                                   r'$x=y$',
                                                                   color='m')
ax.arrow(-5.5, -4.5, 9, 9, color='grey', ls='dashed',
         lw=.5), ax.text(-6, -3, r'$x=y-1$', color='grey')
ax.arrow(-2, -1, 5, 5, color='g', head_width=.2,
         head_length=.2), ax.text(2.9, 4.2, r'$y$', color='g')
ax.arrow(-4.5, 4.5, 9, -9, color='c', ls='dashed', lw=.5), ax.text(-4,
                                                                   4,
                                                                   r'$x=-y$',
                                                                   color='c')
ax.arrow(-2.5, 4.5, 9, -9, color='b', ls='dashed', lw=.5), ax.text(-2,
예제 #19
0
파일: Zad12.py 프로젝트: justynias/AIS
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)]
# y2=[g2(data[i,:]) for i in range(2*N)]
#
# print("Wartości funkcji klasyfikujacych")
# print(y1)
# print(y2)

#decyzje klasyfikatora
decisions = np.array([classifier(data[i, :]) for i in range(2 * N)])
print("Numery klas dla powyższych danych według klasyfikatora:")
예제 #20
0
fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

ax.axhline(linewidth=1.7, color="black")
ax.axvline(linewidth=1.7, color="black")

plt.xticks([])
plt.yticks([])
plt.ylim([ymin, ymax])

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

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)

        
for a in range(-z/2 + 1, z/2 + 1):
    y = f(x, t = u * a)
    ax.plot(x, y, linewidth=1, color="black")

if num != None:
    plt.savefig('envelope' + str(num) + '.png')
    plt.savefig('envelope' + str(num) + '.pdf')

plt.show()
#!/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()
예제 #22
0
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()


#%%
#-------------------------CREANDO FIGURA CON EL USO DE MATPLOTLIB---------------------------------------
# Crear una figura de 8x6 puntos de tamaño, 80 puntos por pulgada
plt.figure(figsize=(8, 6), dpi=80)

# Crear una nueva subgráfica en una rejilla de 1x1
plt.subplot(1, 1, 1)

# Graficar la función escogida con una línea continua azul de 1 pixel de grosor
plt.plot(x, y, color="blue", linewidth=1.0, linestyle="-")
예제 #23
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()
예제 #24
0
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)
        ax.set_ylim([-10, 10])
        ax.set_xlim([-5, 5])

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

    for label in ax.get_ymajorticklabels():
        label.set_rotation(123)

    for points in [(-10, -2.101, "red"), (-2, 0, "green"),
                   (0.001, 10, "blue")]:
        x = np.linspace(points[0], points[1], 100)
        y = 2 / (x**2 + 2 * x)
        ax.plot(x, y, color="green")

    x = np.linspace(-10, 10, 100)
    ax.plot(x, -(2 * (x / x)), "k--")

    y = np.linspace(-10, 10, 100)
    ax.plot(-(2 * (y / y)), y, "k--")

    y = np.linspace(-10, 10, 100)
    ax.plot(0 * y, y, "k--")

    y = np.linspace(-10, 10, 100)
    ax.plot(y, 0 * y, "k--")

    plt.show()
예제 #25
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"]:
예제 #26
0
파일: figure_5.py 프로젝트: tfiers/LFPy
    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)

    # draw measurement points
    ax.plot(PSET.foursphereParams['r'][:, 0],
            PSET.foursphereParams['r'][:, 2],
            'ko',
            label='EEG/MEG sites')

    for i, (x, y, z) in enumerate(PSET.foursphereParams['r']):
        ax.text(x, z + 2500, r'{}'.format(i + 1), ha='center')

    # dipole location
    ax.plot([0],
            [PSET.foursphereParams['radii'][0] + PSET.layer_data['center'][3]],
예제 #27
0
파일: ex_3.py 프로젝트: NelleV/MGRPR
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])
ax.plot(X[my_members, 0], X[my_members, 1],
        'w', markerfacecolor=colors[1], marker = '.')

x_beta = [[i] for i in np.linspace(X.min(), X.max(), 100)]
#y_beta = 1 / beta[0] + np.linspace(x.min(), x.max(), 100) * 1 / beta[1]
y_beta =  (0.5 - u - beta[0] * np.linspace(X.min(), X.max(), 100)) * 1 / beta[1]

ax.plot(x_beta, y_beta, color=colors[2], linewidth=1)

plt.show()

예제 #28
0
ic = [[0.2, 0.2], [0.2, -0.2], [0.2, -0.5], [0.2, 0.7]]
color = ['r', 'b', 'g', 'y']

for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>")
    ax.axis[direction].set_visible(True)
for k in range(len(ic)):
    Y = []
    T = []
    S = []
    r.set_initial_value(ic[k], t0).set_f_params()
    while r.successful() and r.t + dt < tEnd:
        r.integrate(r.t + dt)
        Y.append(r.y)

    S = np.array(np.real(Y))
    ax.plot(S[:, 0], S[:, 1], color=color[k], lw=1.25)

X, Y = np.meshgrid(np.linspace(-5, 5, 40), np.linspace(-5, 5, 20))
U = 1
V = X / Y

N = np.sqrt(U**2 + V**2)
U2, V2 = U / N, V / N
ax.quiver(X, Y, U2, V2)

plt.xlim([-5, 5])
plt.ylim([-5, 5])
plt.ylabel(r"$y$")
plt.show()
예제 #29
0
    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(True)
    ax.axis["xzero"].label.set_text("Axis Zero")

    ax.set_ylim(-2, 4)
    ax.set_xlabel("Label X")
    ax.set_ylabel("Label Y")
    # or
    #ax.axis["bottom"].label.set_text("Label X")
    #ax.axis["left"].label.set_text("Label Y")

    # 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])
    plt.draw()
    plt.show()
예제 #30
0
    tunneling_wave(t, x1, x2, omega, amplitude1, amplitude2) for t in until_x1
]
from_x2 = np.arange(x2 + 0.01, 5 * np.pi, 0.01)
wave_from_x2 = [
    tunneling_wave(t, x1, x2, omega, amplitude1, amplitude2) for t in from_x2
]

colors = initialize_graphics()

fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
#fig, ax = plt.subplots()
fig.set_size_inches(cm2inch([10, 5]))

ax.plot(full_range, potential, lw=2, color=colors[2])
ax.plot(until_x1, wave_until_x1, lw=2, color=colors[0])
ax.plot(from_x2, wave_from_x2, lw=2, color=colors[0])

ax.annotate('$U(x)$', xy=(x2, V0), xytext=(x2 + 0.3, V0 - 0.2))

ax.set_frame_on(False)
#ax.axes.get_yaxis().set_visible(False)
ax.axes.get_xaxis().set_ticks([x1, x2, 5 * np.pi + 0.5])
ax.axes.get_xaxis().set_ticklabels(['$x_1$', '$x_2$', '$x$'])
ax.axis["xzero"].set_axisline_style("-|>")
ax.axis["xzero"].set_visible(True)
ax.axis["yzero"].set_visible(False)

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)
예제 #31
0
"""

#!/usr/bin/python
print "content-type: text/html\n"
import cgitb
cgitb.enable()

import os
os.environ['HOME']='/~charles.zhang/Grapher'
import matplotlib
matplotlib.use('Agg')
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.cos(x*np.pi))

    plt.show()
예제 #32
0
파일: figure_2.py 프로젝트: torbjone/LFPy

# panel D. Illustration of 4-sphere volume conductor model geometry
# ax3.set_title('four-sphere volume conductor model')
for direction in ["xzero"]:
    ax3.axis[direction].set_visible(True)

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


theta = np.linspace(0, np.pi, 31)

# draw some circles:
for i, r, label in zip(range(4), foursphereParams['radii'], ['brain', 'CSF', 'skull', 'scalp']):
    ax3.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)

# draw measurement points
ax3.plot(foursphereParams['r'][:, 0], foursphereParams['r'][:, 2], 'ko', label='EEG/MEG sites')
for i, (x, y, z) in enumerate(foursphereParams['r']):
    # theta = np.arcsin(x / foursphereParams['radii'][-1])
    # if x >= 0:
    #     ax3.text(x, z+5000, r'${}\pi$'.format(theta / np.pi))
    # else:
    #     ax3.text(x, z+5000, r'${}\pi$'.format(theta / np.pi), ha='right')
    ax3.text(x, z+2500, r'{}'.format(i + 1), ha='center')
    
# dipole location
ax3.plot([0], [dipole_position[-1]], 'k.', label='dipole site')
ax3.axis('equal')
ax3.set_xticks(np.r_[-np.array(foursphereParams['radii']), 0, foursphereParams['radii']])
예제 #33
0
파일: newone.py 프로젝트: beeleb/repository
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等分される
    b = f(r, a)
    ax.plot(a, b, 'k', linewidth=0.5, alpha=1)
# linewidth:線の太さ, alpha:濃さ(1以下), 黒色の線は'k'
plt.show()
# plt.savefig('envelopeX.png', bbox_inches='tight', pad_inches=0)
# plt.savefig('test2.pdf,bbox_inches='tight',pad_inches=0)
# それぞれ画像保存用,PDF保存用
예제 #34
0
plt.ylim(-3.5,6.5)


# 図を描く条件設定

# 元になる関数を定義
def f(x, t):
    return t * x - t**2

# 変数
savever = 'png' # 'png' or 'pdf'
fignum = 0 # 0 or 1

if fignum == 0:  
    p = 5    #xの範囲 -p<=x<=p (左右対称にするため)
    r = 2    #tの範囲 -r<=t<=r (同上)
    n = 12   #接線の本数

if fignum == 1:
    p = 5
    r = 3
    n = 30
	
# 包絡線を作る
x = np.linspace(-p,p,2)    # 直線なのでプロットする点は2点でいいかと。xはリストと同じ性質(?)なのに、どうしてf関数のxに入れるのかわかりません。(arrayだから?)
t = np.linspace(-r,r,n)  # 傾きはn-1等分で均等に。lispaceで範囲内をn-1等分したarray(配列?)を用意。
for i in t:
	y = f(x, t=i)
	ax.plot(x, y, 'k-', linewidth=1.0, alpha=0.6)
plt.savefig('envelope' + str(fignum) + '.' + savever)
plt.show()
예제 #35
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()
예제 #36
0

def g2(x):
    return x[0] - x[1]


#klasyfikator
def classifier(x):
    if g1(x) > g2(x):
        return 1
    else:
        return 2


#powierzchnia decyzyjna
#-x[0]+x[1]=x[0]-x[1]
# x[0]=x[1]

fig = plt.figure("Powierzchnia deycyzjna")
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([-10, 10], [-10, 10])
plt.show()
# 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]:
        X.append(x)
        Y.append(y)

# Plot the coordinate pairs and connect each subsequent pair with a basic line
ax.plot(X,Y, color='red', linewidth=.75)
plt.margins(.25)
plt.show()
예제 #38
0
class graph():

	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)

		

	def make_graph(self, f):
		I = f.behaviour("largest interval")

		ps = float(I.args[0])
		pe = float(I.args[1])
		t = np.arange(ps, pe, 0.01)

		self.ax.plot(t, f.eval_np(t))


	def make_graphs(self, *functions,Interval=None):
		if(Interval == None):
			f = functions[0]
			I = f.behaviour("largest interval")
			l,r = float(I.args[0]), float(I.args[1]) 
			for f in functions:
				I = f.behaviour("largest interval")
				l,r = min(l,float(I.args[0])), max(r,float(I.args[1]))
		else:
			l,r = float(Interval.args[0]), float(Interval.args[1]) 

		self.Interval = sp.Interval(l,r)
		
		

		t = np.arange(l,r,.01)

		for f in functions:
			self.ax.plot(t,f.eval_np(t))



	def make_secent(self,f,x1,x2):
		I = f.behaviour("largest interval")

		ps = float(I.args[0])
		pe = float(I.args[1])
		t = np.arange(ps, pe, 0.01)

		sec = f.secent_line(x1,x2)
		self.ax.plot(t, sec.eval_np(t))
		self.plot_point(x1, sec.eval_np(x1))
		self.plot_point(x2,sec.eval_np(x2))



	def make_tangent(self,f,x):
		I = f.behaviour("largest interval")
		ps = float(I.args[0])
		pe = float(I.args[1])
		t = np.arange(ps, pe, 0.01)

		tan = f.tangent_line(x)
		self.ax.plot(t, tan.eval_np(t))
		self.plot_point(x, tan.eval_np(x))



	def plot_point(self, x, y):
		self.ax.plot(np.array([x]), np.array([y]), 'ro')


	def zoom_y(self, f, I):
		self.zoom_x(I)
		self.zoom_y(f.range(I))

	def zoom_x(self,I):
		ps = float(I.args[0])
		pe = float(I.args[1])

		self.ax.set_xlim(ps,pe)

	def zoom_y(self,I):
		ps = float(I.args[0])
		pe = float(I.args[1])

		self.ax.set_ylim(ps,pe)
	def show(self):
		return self.fig
예제 #39
0
#
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))
ax2.grid()
mohr_circle, = ax2.plot([], [], '.r',label='Etat de contrainte', markersize=2)

ax2.legend()


# ########################

def Snn_Snt_decomposition (Sigma, n) :
    # Check that norm of n is one
    n=n/np.linalg.norm(n)
    
    # Flux stress vectir
    phi=np.dot(Sigma,n)
    
    # Normal stress component
    Snn=np.dot(phi,n)
예제 #40
0
def f(x, t):
    return t * x - t**2  # 関数fの定義

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

    ax.axhline(linewidth=1.7, color="black")
    ax.axvline(linewidth=1.7, color="black")

    plt.xticks([])
    plt.yticks([])
    plt.ylim([-20,40])

    ax.text(0, 1.05, '$y$', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.05, 0, '$x$', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')
    # 軸の書式設定(謎)

    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(-10, 10, 200)
    for i in range(-5,6):  # グラフを書く作業を繰り返す範囲
        y = f(x, t=i)
        ax.plot(x, y, 'black', linewidth=2)
    plt.show()
예제 #41
0
파일: 04_02.py 프로젝트: butuzov/CS122-KPI
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)
    ax.plot(x, 3**((2*x)/(3*x+1)))


    plt.show()
예제 #42
0
파일: 04_01.py 프로젝트: butuzov/CS122-KPI
    ax.axhline(linewidth=.7, color="black")
    ax.axvline(linewidth=.7, color="black")

    ax.text(0, 1.05, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.05, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')
    #
    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)

    for label in ax.get_ymajorticklabels():
        label.set_rotation(123)

    x = np.linspace(-4, 0, 100) # x < 0
    f1, = ax.plot(x, -(x), label="-x")

    x = np.linspace(0, 2, 10000) # x < 0
    x = x[1:len(x)-1]
    f2, = ax.plot(x, -(x-1)**2, label="-(x-1)^2")
    #
    x = np.linspace(2, 4, 100) # x < 0
    f3, = ax.plot(x, (x-3), label="x-3")

    plt.legend(handles=[f1,f2,f3], loc=1)

    plt.show()
예제 #43
0
                        0,
                        width=6,
                        scale=1,
                        units='x',
                        label=r'$\sigma_{nn}$',
                        color='c')
vec_Snt_xy = ax1.quiver(0,
                        0,
                        0,
                        0,
                        width=6,
                        scale=1,
                        units='x',
                        label=r'$\sigma_{nt}$',
                        color=(1.0, 0.25, 0.75))
line_proj, = ax1.plot([], [], '--')

facette, = ax1.plot([], [], '--g', lw=2)
vec_n = ax1.quiver(0,
                   0,
                   0,
                   0,
                   width=4,
                   scale=4 / Sig_max,
                   units='x',
                   label=r'$n$',
                   color='g')
ax1.legend()

# Espace Snn,Snt
ax2 = SubplotZero(fig, 122)
예제 #44
0
파일: code_fig.py 프로젝트: botplex/blog
import numpy

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

    ax.axhline(linewidth=1.7, color="black")
    ax.axvline(linewidth=1.7, color="black")

    plt.xticks(range(5))
    plt.yticks(range(1,5))

    ax.text(0, 1.05, '$x_{2}$', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.025, 0, '$x_{1}$', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

    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 = numpy.linspace(-1, 3.5, 1000)
    y = (4 - 2*x)
    ax.plot(x,y)

    plt.annotate('$y=1$',xy=(1.75,1.5))
    plt.annotate('$y=0$',xy=(0.5,1))

    plt.show()
예제 #45
0
파일: figure_5.py 프로젝트: torbjone/LFPy
    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)
    
    # draw measurement points
    ax.plot(PSET.foursphereParams['r'][:, 0], PSET.foursphereParams['r'][:, 2], 'ko', label='EEG/MEG sites')
    
    for i, (x, y, z) in enumerate(PSET.foursphereParams['r']):
        ax.text(x, z+2500, r'{}'.format(i+1), ha='center')
        
    # dipole location
    ax.plot([0], [PSET.foursphereParams['radii'][0] + PSET.layer_data['center'][3]], 'k.', label='dipole site')
    
    ax.axis('equal')
    ax.set_ylim(top=max(PSET.foursphereParams['radii']) + 5000)

    ax.set_xticks(np.r_[-np.array(PSET.foursphereParams['radii']), 0, PSET.foursphereParams['radii']])
    ax.set_xticklabels([])                       
예제 #46
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()

예제 #47
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()
예제 #48
0
def main():
	opts, args = getopt.getopt(sys.argv[1:], 'u:', ['URL='])
	print("Number of arguments: " + str(len(sys.argv)))

	if len(sys.argv) > 1:
		threadID = str(sys.argv[1])
	else:
		threadID = '3jms68'

	print("Using thread: " + threadID)

	r = praw.Reddit(user_agent='test script /u/Speff')
	#r.set_oauth_app_info(client_id='aDjUAlJ0Cb17pA',
	#						client_secret='AeJjd7CLEUt7wyMmTVhP6kidhLc',
	#						redirect_uri='http://127.0.0.1:65010/'
	#						'authorize_callback')
	#url = r.get_authorize_url('uniqueKey', 'identity', True)
	#print(url)
	#access_information = r.get_access_information('lfJfhgKEDDUzgwY9a2tcVtVYMnc')
	#r.set_access_credentials(**access_information)
	#authenticated_user = r.get_me()
	#print(authenticated_user.name, authenticated_user.link_karma)

	start = float(time.time())
	submission = r.get_submission(submission_id=threadID, comment_sort="confidence")
	submission.replace_more_comments(limit=None, threshold=1)
	print("Seconds to process thread: " + str(time.time()-start))
	flat_comments = praw.helpers.flatten_tree(submission.comments)

	submission_score = submission.score
	submission_time = submission.created_utc

	comment_score = []
	comment_time = []
	commentInfo = []
	#comment_body = []

	print("Number of comments: " + str(len(flat_comments)))

	for x in flat_comments:
	#	print(x.body + "\n")
		comment_score.append(abs(x.score-1)+1)
		comment_time.append((x.created_utc - submission_time)/(60))
	#	comment_body.append(x.body)


	data = np.column_stack((comment_time, comment_score))

	uniques, count = np.unique(data[:,1], return_counts=True)
	unvoted = 0.0
	for x in range(0, len(uniques)):
		if(uniques[x]) == 1:
			unvoted = count[x]

	unvoted = unvoted / len(comment_time)

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

		ax.axis["left"].set_label('Points')
		ax.axis["bottom"].set_label('Time (minutes)')

		xRange = np.amax(data[:,0]) - np.amin(data[:,0])
		yRange = np.amax(data[:,1]) - np.amin(data[:,1])

		plt.axhline(1, color='gray', linestyle='--')
		plt.axhline(0, color='black')
		plt.axvline(0, color='black')

		xFit = np.linspace(np.amin(data[:,0]) - xRange*0.1, np.amax(data[:,0]) + xRange*0.1, 1000)

		A, K, C = fit_exp_nonlinear(data[:,0], data[:,1])
		fit_y = 2*model_func(xFit, A, K, C)


		print("Best-fit polynomial coefficient(s): " + str((A, K, C)))

		ax.axis([np.amin(data[:,0]) - xRange*0.1, np.amax(data[:,0]) + xRange*0.1, np.amin(data[:,1]) - yRange*0.1, np.amax(data[:,1]) + yRange*0.1])
		ax.plot(data[:,0], data[:,1], '.')
		ax.plot(xFit, fit_y, '-', color='darkred')

		ax.text(0.75*xRange + np.amin(data[:,0]), 0.9*yRange + np.amin(data[:,1]), str(round(unvoted,3)*100) + '% unvoted \n', fontsize=15)

		plt.show()
예제 #49
0
# panel D. Illustration of 4-sphere volume conductor model geometry
# ax3.set_title('four-sphere volume conductor model')
for direction in ["xzero"]:
    ax3.axis[direction].set_visible(True)

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

theta = np.linspace(0, np.pi, 31)

# draw some circles:
for i, r, label in zip(range(4), foursphereParams['radii'],
                       ['brain', 'CSF', 'skull', 'scalp']):
    ax3.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)

# draw measurement points
ax3.plot(foursphereParams['r'][:, 0],
         foursphereParams['r'][:, 2],
         'ko',
         label='EEG/MEG sites')
for i, (x, y, z) in enumerate(foursphereParams['r']):
    # theta = np.arcsin(x / foursphereParams['radii'][-1])
    # if x >= 0:
    #     ax3.text(x, z+5000, r'${}\pi$'.format(theta / np.pi))
    # else:
    #     ax3.text(x, z+5000, r'${}\pi$'.format(theta / np.pi), ha='right')
    ax3.text(x, z + 2500, r'{}'.format(i + 1), ha='center')
예제 #50
0
from mpl_toolkits.axes_grid.axislines import SubplotZero

x = linspace(-5 * pi, 5 * pi, 500)
y = (sin(x) / x)**2
fig = plt.figure(figsize=(8, 4))
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
ax.grid(True)
ax.set_xticks([
    -5 * pi, -4 * pi, -3 * pi, -2 * pi, -pi, 0, pi, 2 * pi, 3 * pi, 4 * pi,
    5 * pi
])
ax.set_xticklabels([
    "$-5 \pi$", "$-4 \pi$", "$-3 \pi$", "$-2 \pi$", "$- \pi$", "0", "$\pi$",
    "$2 \pi$", "$3 \pi$", "$4 \pi$", "$5 \pi$"
])
ax.set_ylim((-.3, 1.2))
ax.set_yticklabels([])
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, y, label=r"$sinc^{2} \ x$", color="k", linewidth=3, alpha=0.8)
ax.text(5.5 * pi, 0., "x")
ax.text(0.1, 1, "1")
ax.legend()
plt.tight_layout()
plt.savefig("sinc.png")
plt.show()
until_x1 = np.arange(0.0, x1, 0.01)
wave_until_x1 = [tunneling_wave(t, x1, x2, omega, amplitude1, amplitude2) for t in until_x1]
from_x2 = np.arange(x2+0.01, 5*np.pi, 0.01)
wave_from_x2 = [tunneling_wave(t, x1, x2, omega, amplitude1, amplitude2) for t in from_x2]


colors=initialize_graphics()

fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
#fig, ax = plt.subplots()
fig.set_size_inches(cm2inch([10,5]))

ax.plot(full_range, potential, lw=2, color=colors[2])
ax.plot(until_x1, wave_until_x1, lw=2, color=colors[0])
ax.plot(from_x2, wave_from_x2, lw=2, color=colors[0])

ax.annotate('$U(x)$', xy=(x2, V0), xytext=(x2+0.3, V0-0.2))

ax.set_frame_on(False)
#ax.axes.get_yaxis().set_visible(False)
ax.axes.get_xaxis().set_ticks([x1, x2, 5*np.pi+0.5])
ax.axes.get_xaxis().set_ticklabels(['$x_1$','$x_2$', '$x$'])
ax.axis["xzero"].set_axisline_style("-|>")
ax.axis["xzero"].set_visible(True)
ax.axis["yzero"].set_visible(False)

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)
예제 #52
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()
예제 #53
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")
예제 #54
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()