コード例 #1
0
ファイル: main.py プロジェクト: avery-laird/themartian
def main():
    re = []
    rm = []
    t = []
    ve = []
    vm = []
    earth = Planet()
    earth.set_e(0.0167)
    earth.set_rmin(1.471E11)
    earth.set_period(365*86400)
    earth.set_semi_major_axis(149600000)
    mars = Planet()
    mars.set_e(0.09341233)
    mars.set_rmin(2.0662E11)
    mars.set_period(687*86400)
    mars.set_semi_major_axis(227920000)
    
    for x in range(0, int(sys.argv[1])):
        re.append(earth.step())
        rm.append(mars.step())
        ve.append(earth.velocity())
        vm.append(mars.velocity())
        t.append(earth.theta)
        sys.stdout.write("\rStep " + str(earth.count) + " / " + sys.argv[1] + " " + str((float(earth.count)/float(sys.argv[1]))*100) + "% " + str(earth.theta) + " " + str(mars.theta))
        sys.stdout.flush()
 	
    print "\n"
    plt.figure(1)
    plt.polar(t, re)
    plt.polar(t, rm)

    plt.figure(2)
    plt.plot(t, ve)
    plt.plot(t, vm)
    plt.show()
コード例 #2
0
ファイル: genplotlib.py プロジェクト: acvmanzo/mn
def plot_phaseplot_lpf(dictdata, keys, autok, title, withn='yes'):
    colors = ['r', 'b', 'g', 'y', 'k']
    
    plt.suptitle(title, fontsize='large' )
    if autok == 'yes':
        k = dictdata.keys()
    
    for i, condition in enumerate(keys):
        datac = colors[i]
        data = dictdata[condition]
        
        try:
            n = len(data)
            theta, r = zip(*data)
        except TypeError:
            theta, r = data
            n = 1
        if withn == 'yes':
            plt.polar(theta, r, 'o', color=datac, label=condition + '\n n=' + str(n))
        if withn == 'no':
            plt.polar(theta, r, 'o', color=datac, label=condition)

        #lines, labels = plt.rgrids( (1.0, 1.4), ('', ''), angle=0 )
        tlines, tlabels = plt.thetagrids( (0, 90, 180, 270), ('0', 'pi/2', 'pi', '3pi/2') )
        leg = plt.legend(loc=(0.95,0.75))
  
        for t in leg.get_texts():
            t.set_fontsize('small')
            
        plt.subplots_adjust(top=0.85)
        plt.draw()
コード例 #3
0
ファイル: s2p.py プロジェクト: Daimyo/s2p
 def plot_SParameters(self, S='S21' , style='MA'):
     '''plot  S parameter from data
         
         Input:
             - S (String) ["S11", "S12", "S21", "S22"]: Set which parameter you want to plot
             - asked_format ("String") ["MA", "DB", "RI"]: Set in which format we would like to have plot
         
         Output:
             - matplotlib 2d figure
     '''
     
     x, y, z = self.get_SParameters(S, style)
     
     factor = self.get_frequency_unit(style='Float')
 
     if factor == 1. :
         x_label = 'Frequency [Hz]'
     elif factor == 1e3 :
         x_label = 'Frequency [kHz]'
     elif factor == 1e6 :
         x_label = 'Frequency [MHz]'
     elif factor == 1e9 :
         x_label = 'Frequency [GHz]'
     
     fig = plt.figure()
     
     
     if re.match('^[mM][aA]$', style) :
         
         ax1 = fig.add_subplot(211)
         ax1.plot(x, y, label=S)
         plt.ylabel('Amplitude [V]')
         plt.grid()
     elif re.match('^[dD][bB]$', style) :
         
         ax1 = fig.add_subplot(211)
         ax1.plot(x, y, label=S)
         plt.ylabel('Attenuation [dB]')
         plt.grid()
     
     
     if re.match('^[dD][bB]$|^[mM][aA]$', style):
     
         ax2 = fig.add_subplot(212, sharex = ax1)
         ax2.plot(x, z, label=S)
         plt.ylabel('Phase [deg]')
         plt.xlabel(x_label)
     elif re.match('^[rR][iI]$', style):
     
         ax1 = fig.add_subplot(111)
         y = y*1./y.max()
         plt.polar(y, z, label=S)
         plt.title('Normalised amplitude')
         plt.ylabel('Real part')
         plt.ylabel('Imaginary part')
     
     
     plt.legend(loc='best')
     plt.grid()
     plt.show()
コード例 #4
0
ファイル: test_axes.py プロジェクト: keltonhalbert/matplotlib
def test_polar_units():
    import matplotlib.testing.jpl_units as units
    from nose.tools import assert_true
    units.register()

    pi = np.pi
    deg = units.UnitDbl( 1.0, "deg" )
    km = units.UnitDbl( 1.0, "km" )

    x1 = [ pi/6.0, pi/4.0, pi/3.0, pi/2.0 ]
    x2 = [ 30.0*deg, 45.0*deg, 60.0*deg, 90.0*deg ]

    y1 = [ 1.0, 2.0, 3.0, 4.0]
    y2 = [ 4.0, 3.0, 2.0, 1.0 ]

    fig = plt.figure()

    plt.polar( x2, y1, color = "blue" )

    # polar( x2, y1, color = "red", xunits="rad" )
    # polar( x2, y2, color = "green" )

    fig = plt.figure()

    # make sure runits and theta units work
    y1 = [ y*km for y in y1 ]
    plt.polar( x2, y1, color = "blue", thetaunits="rad", runits="km" )
    assert_true( isinstance(plt.gca().get_xaxis().get_major_formatter(), units.UnitDblFormatter) )
コード例 #5
0
 def drawPair(self, pair, label):
     start_angle = self.hourToAngle(pair[1])
     end_angle = self.hourToNextAngle(pair[0], start_angle)
     new_angles = np.linspace(start_angle, end_angle, 20)
     new_points = np.ones(len(new_angles))
     plt.polar(new_angles, new_points)
     plt.fill_between(new_angles, new_points, facecolor='yellow', alpha=0.5)
     self.drawLabel(new_angles, new_points, label)
コード例 #6
0
ファイル: fibonacci.py プロジェクト: klho/klho.github.io
def floret_revolutions(n, **kwargs):
  r = np.arange(n)
  F = fibonacci_lim(r[-1])
  plt.figure(figsize=(6,6))
  plt.polar(np.mod(r/phi,1)*2*np.pi, r, '.', **kwargs)
  plt.polar(np.mod(F/phi,1)*2*np.pi, F, 'r.', **kwargs)
  plt.gca().set_rticks([])
  plt.show()
コード例 #7
0
ファイル: stretchy.py プロジェクト: r3/Stretchy
def display_picture(points):
    """Graphs the points given on a polar coordinate grid"""
    r_vals = []
    theta_vals = []
    for r, theta in points:
        r_vals.append(r)
        theta_vals.append(theta)

    pyplot.polar(r_vals, theta_vals, linestyle='solid', marker='o')
    pyplot.show()
コード例 #8
0
ファイル: OrbitalElements.py プロジェクト: stuv/orbit
	def plot_orbit(self):
		ta = self.trueAnom()
		sma = self.smAxis()[0]
		e = self.ecc()
		theta = np.linspace(0,2*math.pi,360)
		r=(sma*(1-e**2))/(1+e*np.cos(theta))
		plt.polar(theta, r)
		print(np.c_[r,theta])
		plt.savefig("Orbit.png")
		plt.show()
コード例 #9
0
ファイル: love.py プロジェクト: leriomaggio/nerdy_love
def my(heart):
    r, t = heart
    plt.polar(r, t, 'r', lw=5)
    tick_params = {'axis':'y', 'which':'both', 
                   'bottom': False, 'top':False, 
                   'left': False, 'right': False,
                   'labelbottom': False, 'labelleft': False}
                   
    plt.tick_params(**tick_params)
    plt.show()
コード例 #10
0
 def plot_diff_cross_sect(self, **kwargs):
     """Displays a plot of the differential cross section.
     
     Arguments:
        **kwargs: Any additional arguments to plot
     Returns:
        Displays the plot
     """
     
     tgrid = np.linspace(-np.pi,np.pi,361)
     plt.polar(tgrid,self.diff_cross_sect(tgrid), marker='.', **kwargs)
     plt.show()
コード例 #11
0
def test_polar_units():
    import matplotlib.testing.jpl_units as units
    units.register()
    pi = np.pi
    deg = units.UnitDbl( 1.0, "deg" )
    x1 = [ pi/6.0, pi/4.0, pi/3.0, pi/2.0 ]
    x2 = [ 30.0*deg, 45.0*deg, 60.0*deg, 90.0*deg ]
    y1 = [ 1.0, 2.0, 3.0, 4.0]
    y2 = [ 4.0, 3.0, 2.0, 1.0 ]
    fig = plt.figure()
    plt.polar( x2, y1, color = "blue" )
    fig.savefig( 'polar_units' )
コード例 #12
0
def polar_demo():
    """Make a polar plot of some random angles.

    """

    # Sample a bunch of random angles
    A = rand.randint(0, 360, 100)
    # Plot each angle as a point with radius 1
    plt.figure()
    plt.polar(A, np.ones_like(A), 'ko')
    # Disable y-ticks, because they are distracting
    plt.yticks([], [])
    plt.title("Polar Demo", fontsize=titlesize)
コード例 #13
0
ファイル: fibonacci.py プロジェクト: klho/klho.github.io
def show_floret_growth(theta, r, prefix='frame', grow=True, ms=10):
  n = len(r)
  savefmt = prefix + '%0' + str(len(str(n-1))) + 'i.png'
  plt.figure(figsize=(6,6))
  for i in range(n):
    plt.clf()
    if grow: s = float(n - i - 1) / n
    else:    s = 0.
    plt.polar(theta[:i+1], r[:i+1]-s, '.', mec='k', mfc='b', ms=ms)
    plt.polar(theta[i], r[i]-s, '.', mec='k', mfc='r', ms=ms)
    plt.gca().set_rlim([0, 1])
    plt.gca().set_rticks([])
    plt.savefig(savefmt %i)
コード例 #14
0
def main():
    earth = Body([0, 147090000000], 2929000, 5.9726E24, Orbit(0.016710219, 149600000000, 1.495583757E8, 365))
#    print earth.orbit.radius_from_angle(math.pi)
#    print earth.orbit.find_e_anomaly(271433.6, 0.016710219)
#    print earth.orbit.find_true_anomaly(earth.orbit.find_e_anomaly(271433.6, 0.016710219))
    theta = []
    radius = []
    for time in [3]:
        earth.orbit.calc_position(time)
        theta.append(earth.orbit.true_anomaly)
        radius.append(earth.orbit.radius)
    plt.polar(theta, radius, 'o')
    plt.show()
コード例 #15
0
ファイル: satellite_fern.py プロジェクト: jackhall/Claude
def plot_phase(control=None, state0=None):
	"""generates a phase portrait and phase trajectory from initial conditions"""
	#time = np.linspace(0, 20, 100) not needed for simulate()
	
	results, time = simulate(100, 10, control, state0)
	theta, h = results[:,0], results[:,1]
	state0 = (theta[0], h[0])
	#statew = [theta[-1], h[-1]]
	#print "Final: ", statew
	
	#system trajectory
	plot.figure(1) 
	plot.plot(theta, h, color='green') #use polar(theta, h)?
	plot.figure(2)
	plot.polar(theta, h, color='green')
		
	#phase portrait (vector field)
	thetamax, hmax = max(abs(theta)), max(abs(h))
	theta, h = numpy.meshgrid(numpy.linspace(-thetamax, thetamax, 10), 
				  numpy.linspace(-hmax, hmax, 10))
	Dtheta, Dh = numpy.array(theta), numpy.array(h)
	for i in range(theta.shape[0]):
		for j in range(theta.shape[1]):
			Dtheta[i,j] = dtheta(float(theta[i,j]), float(h[i,j]))
			Dh[i,j] = dh(float(theta[i,j]), float(h[i,j]))
	
	plot.figure(1)
	plot.quiver(theta, h, Dtheta, Dh) #no polar equivalent...
	
	#optimal path mode
	h = numpy.linspace(-hmax, hmax, 100)
	plot.plot(path(h), h, color='blue') #use polar(theta, h)?
	if control is None:
		plot.savefig("optimal-satellite-cart.png", dpi=200)
	else:
		plot.savefig("satellite-nonoptimal-cart.png", dpi=200)
	plot.xlabel("angle (rad)")
	plot.ylabel("angular momentum (N-m-s)")
	
	#optimal mode in polar
	plot.figure(2)
	plot.polar(path(h), h, color='blue')
	if control is None:
		plot.savefig("optimal-satellite-polar.png", dpi=200)
	else:
		plot.savefig("satellite-nonoptimal-polar.png", dpi=200)
	plot.xlabel("angle (rad)")
	plot.ylabel("angular momentum (N-m-s)")
	
	plot.plot(state0[0], state0[1], 'o', color='green')
	plot.show()
コード例 #16
0
def test_polar_wrap():
    D2R = np.pi / 180.0
    fig = plt.figure()
    plt.subplot( 111, polar=True, resolution=1 )
    plt.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" )
    plt.polar( [179*D2R,  181*D2R], [0.2, 0.1], "g.-" )
    plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
    fig.savefig( 'polar_wrap_180' )
    fig = plt.figure()
    plt.subplot( 111, polar=True, resolution=1 )
    plt.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" )
    plt.polar( [2*D2R,  358*D2R], [0.2, 0.1], "g.-" )
    plt.polar( [358*D2R,  2*D2R], [0.2, 0.1], "r.-" )
    plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
    fig.savefig( 'polar_wrap_360' )
コード例 #17
0
ファイル: measurement.py プロジェクト: odebeir/ivctrack
def relative_direction_distribution(xy,verbose=False):
    """computes instantaneous directions and make an histogram centered on previous direction
    """
    dxy = xy[1:,:]-xy[0:-1,:]
    theta = npy.arctan2(dxy[:,0],dxy[:,1])
    rho = npy.sqrt(npy.sum(dxy**2,axis=1))
    dtheta = theta[1:]-theta[0:-1]
    dtheta = npy.hstack(([0],dtheta))
    #verify that theta is in [-pi,+pi]
    clip_dtheta = dtheta.copy()
    clip_dtheta[dtheta>npy.pi] = dtheta[dtheta>npy.pi] - 2.*npy.pi
    clip_dtheta[dtheta<-npy.pi] = dtheta[dtheta<-npy.pi] + 2.* npy.pi

    #resulting direction and dispersion
    (R,V,Theta,Rtot) = rayleigh(rho,clip_dtheta)

    #distribution
    N = 8
    width = 2*npy.pi/N
    offset_th = .5*width
    bins = npy.linspace(-npy.pi-offset_th,npy.pi+offset_th,N+2,endpoint=True)
    h_theta,bin_theta = npy.histogram(clip_dtheta,bins=bins,weights=rho) # ! weighted histogram
    #grouping first and last bin corresponding to the same direction
    h_theta[0]+=h_theta[-1]

    if verbose:
        import matplotlib.pyplot as plt

        fig=plt.figure()
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True,)
        #    #plot polar histogram bins
        #    ax.bar(bin_theta[0:-1], npy.ones_like(bin_theta[0:-1]), width=width, bottom=0.0,alpha=.5)

        #plot polar distribution
        ax.bar(bin_theta[0:-2], h_theta[:-1], width=width, bottom=0.0,label='rel.direction hist.')
        #plot relative displacement
        plt.polar(clip_dtheta,rho, 'yo',label='rel.direction')

        #plot main direction and dispersion
        plt.polar(Theta,R*Rtot,'ro',label='avg.')
        ax.bar(Theta-V/2, R*Rtot*.01, color='k',width=V, bottom=R*Rtot,label='dispersion')
        ax.legend(loc='upper left')
        #plot xy trajectory
        ax = fig.add_axes([0.1, 0.1, 0.2, 0.2])
        plt.plot(xy[:,0],xy[:,1])
        plt.plot(xy[0,0],xy[0,1],'k+')
        plt.show()
    return (R,V,Theta,Rtot,clip_dtheta,rho)
コード例 #18
0
ファイル: skybrick.py プロジェクト: sbailey/skybrick
def outlinebrick(brick, polar=False):
    import matplotlib.pyplot as plt
    if polar:
        n = 20
        x = np.linspace(brick.ra_min, brick.ra_max, n) * np.pi / 180
        ra = np.concatenate([x, x[-1::-1]])
        dec = np.concatenate([np.ones(n)*brick.dec_min, np.ones(n)*brick.dec_max])
        if brick.dec_min < 0:
            dec = dec + 90
        else:
            dec = 90 - dec
        plt.polar(ra, dec, 'k-', lw=2)
    else:
        x = [brick.ra_min, brick.ra_max, brick.ra_max, brick.ra_min, brick.ra_min]
        y = [brick.dec_min, brick.dec_min, brick.dec_max, brick.dec_max, brick.dec_min]
        plt.plot(x, y, 'k-', lw=2)
コード例 #19
0
def process_ellipse(normPower, theta1RadFinal, figWidth, figHeigth, dir, number):
    """
    :param normPower:
    :param theta1RadFinal:
    :param figWidth: width of the figure
    :param figHeigth: height of the figure
    :param dir: full path to the directory where one wants to store the intermediate images
    :param number:
    :return:
    """
    # Combine data into [XY] to fit to an ellipse
    Mirtheta1RadFinal1 = np.concatenate([theta1RadFinal.T, (theta1RadFinal + np.pi).T])
    MirnormPower = np.concatenate([normPower.T, normPower.T])

    # Convert mirrored polar coords to cartesian coords
    xdata, ydata = pol2cart(Mirtheta1RadFinal1, MirnormPower)
    ell_data = np.vstack([xdata, ydata])
    ell_data = ell_data.T

    # Python fitting function, see EllipseDirectFit
    A, centroid = EllipseDirectFit(ell_data)
    t = orientation(A)

    # Plot Lower Left - Polar plot of angular distribution
    angDist = plt.figure(figsize=(figWidth, figHeigth))  # Creates a figure containing angular distribution.
    r_line = np.arange(0, max(MirnormPower) + .5, .5)
    th = np.zeros(len(r_line))
    for i in range(0, len(r_line)):
        th[i] = t
    th = np.concatenate([th, (th + 180)])
    r_line = np.concatenate([r_line, r_line])
    plt.polar(Mirtheta1RadFinal1, MirnormPower, color ='k', linewidth=2)
    plt.polar(th * pi / 180, r_line, color='r', linewidth=3)

    if (max(MirnormPower)<2):
        inc = 0.5
    elif (max(MirnormPower)<5):
        inc = 1
    elif max(MirnormPower)<20:
        inc = 5
    else:
        inc = 10
    plt.yticks(np.arange(inc, max(MirnormPower), inc), **ticksfont)
    plt.xticks(**ticksfont)
    angDist.savefig(dir+'angDist_' + number.__str__(), bbox_inches='tight')
    plt.close()
    return t, angDist
コード例 #20
0
ファイル: bandwidth.py プロジェクト: carlkl/mw_suite
def trace_process(data, s11=True, plot=True):
    """Calculate the bandwidth from VNA trace data."""
    # Columns of data are: freq (Hz), mag (dB), phase (deg)
    if s11:
        peak_freq = np.argmin(data[:, 1])
    else:
        peak_freq = np.argmax(data[:, 1])

    phase_at_peak = data[peak_freq, 2]
    # subtract phase from all measurements and convert to radians
    data[:, 2] = (data[:, 2] - phase_at_peak)*np.pi*0.00555555555
    # convert dB S11 to lin S11
    data[:, 1] = 10 ** (data[:, 1] / 20)
    # convert to complex and then to imaginary
    imaginary_part = data[:, 1]*np.sin(data[:, 2])
    # find max and min imaginary
    freq_imag_min = data[np.argmin(imaginary_part), 0]
    freq_imag_max = data[np.argmax(imaginary_part), 0]

    # printing extras
    format_string = "Frequency of imaginary {} {:d}"
    flag = "minimum" if s11 else "maximum"
    # Data output
    print("Frequency at {}: {:d} Hz".format(flag, int(data[peak_freq, 0])))
    #print(format_string.format("maximum", int(freq_imag_max)))
    #print(format_string.format("minimum", int(freq_imag_min)))
    bandwidth = abs(freq_imag_max - freq_imag_min)
    print("Bandwidth {:.6f} kHz".format(bandwidth * 1e-3))
    q = data[peak_freq, 0] / bandwidth
    print("Q {:.0f}".format(q))
    if plot is False:
        return
    # Plots
    plt.figure(0, figsize=(8, 5))
    plt.plot(data[:, 0], imaginary_part)
    plt.title("Imaginary vs. frequency")
    plt.savefig("imag.png")
    plt.clf()
    plt.polar(data[:, 2], data[:, 1])  # first phase, then r
    plt.scatter(data[peak_freq, 2], data[peak_freq, 1], c='r', marker='o')
    plt.title("S11 in polar", va="bottom")
    plt.savefig("polar.png")
    plt.clf()
    plt.plot(data[:, 0], data[:, 1])
    plt.title("S11 curve in linear scale")
    plt.savefig("curve.png")
    plt.close("all")
コード例 #21
0
ファイル: PyGS.py プロジェクト: JakeHeb/PyGS
 def PlotPolarDot(self,distance=False):
     """
     Makes a polar plot of the data, TODO: with an optional filter condition
     
     If distance is true, plots against comoving distance rather than redshift.
     """
     
     plt.clf()
     plt.title("Polar Plot of sample "+self.sample_name+" from "+self.survey_name)
     
     if not distance:
         plt.polar(self.survey_data['ra'],self.survey_data['redshift'],'.',markersize=1)
         plt.savefig(self.plots_dir+'/PolarPlot_Redshift.eps')
     else:
         plt.polar(self.survey_data['ra'],self.survey_data['c_dist'],'.',markersize=1)
         plt.savefig(self.plots_dir+'/PolarPlot_Distance.eps')
     plt.show()    
コード例 #22
0
ファイル: MCres.py プロジェクト: ceyzeriat/MCres
 def _map(self, param_x, param_y, data=None, method=np.mean, noplot=False, fig=None, ax=None, cax=None, bin_x=50, bin_y=50, cmap="jet", cm_min=None, cm_max=None, axescolor='w', polar=False, showmax=True, **kwargs):
     """
     Return a 2D histogram of the MC chain, showing the walker density per bin
     """
     if param_x not in self.paramstr or param_y not in self.paramstr:
         print("You must choose param_x and param_y among %s" % self.paramstr)
         return
     x = self.chain[param_x]
     if hasattr(x, 'compressed'): x = x.compressed()
     y = self.chain[param_y]
     if hasattr(y, 'compressed'): y = y.compressed()
     if data is not None:
         H, bin_y, bin_x = binned_statistic_2d(y, x, data, method, bins=(bin_y, bin_x))[:3]
     else:
         H, bin_y, bin_x = np.histogram2d(y, x, bins=(bin_y, bin_x))
     H[np.isnan(H)] = np.nanmin(H)
     maxd = np.unravel_index(np.argmax(H), H.shape)
     if cm_min is None: cm_min = np.min(H)
     if cm_max is None: cm_max = np.max(H)
     cmap, norm, mappable = _core.colorbar(cmap=cmap, cm_min=cm_min, cm_max=cm_max)
     if noplot: return H, bin_y, bin_x, cmap, norm, mappable
     if not polar:
         if fig is None: fig = plt.figure()
         if ax is None: ax = fig.add_subplot(111)
         im = mplimageNonUniformImage(ax, cmap=cmap, norm=norm, interpolation='bilinear')
         arrbin_x = _core.bins_to_array(bin_x)
         arrbin_y = _core.bins_to_array(bin_y)
         im.set_data(arrbin_x, arrbin_y, H)
         ax.images.append(im)
         if showmax is True: ax.plot(arrbin_x[maxd[1]], arrbin_y[maxd[0]], '^w', ms=7)
         ax.set_xlim(bin_x[0], bin_x[-1])
         ax.set_xlabel(param_x)
         ax.set_ylim(bin_y[0], bin_y[-1])
         ax.set_ylabel(param_y)
     else:
         if ax is None: fig, ax = plt.subplots(subplot_kw={'projection':'polar'})
         T,R = np.meshgrid(bin_x,bin_y)
         pax = ax.pcolormesh(T, R, H, cmap=cmap, norm=norm)
         ax.grid(True)
         if showmax is True: plt.polar(T[maxd], R[maxd], '^w', ms=7)
         ax.set_ylim(0, bin_y[-1])
         ax.set_title(param_x+' vs '+param_y)
     ax.grid(True, color=axescolor)
     ax.tick_params(axis='both', colors=axescolor)
     fig.colorbar(mappable, cax=cax)
コード例 #23
0
ファイル: test_axes.py プロジェクト: keltonhalbert/matplotlib
def test_polar_wrap():
    D2R = np.pi / 180.0

    fig = plt.figure()

    plt.subplot(111, polar=True)

    plt.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" )
    plt.polar( [179*D2R,  181*D2R], [0.2, 0.1], "g.-" )
    plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
    assert len(fig.axes) == 1, 'More than one polar axes created.'
    fig = plt.figure()

    plt.subplot( 111, polar=True)
    plt.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" )
    plt.polar( [2*D2R,  358*D2R], [0.2, 0.1], "g.-" )
    plt.polar( [358*D2R,  2*D2R], [0.2, 0.1], "r.-" )
    plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
コード例 #24
0
ファイル: test_axes.py プロジェクト: KiranPanesar/wolfpy
def test_polar_wrap():
    D2R = np.pi / 180.0

    fig = plt.figure()

    #NOTE: resolution=1 really should be the default
    plt.subplot( 111, polar=True, resolution=1 )
    plt.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" )
    plt.polar( [179*D2R,  181*D2R], [0.2, 0.1], "g.-" )
    plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )

    fig = plt.figure()

    #NOTE: resolution=1 really should be the default
    plt.subplot( 111, polar=True, resolution=1 )
    plt.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" )
    plt.polar( [2*D2R,  358*D2R], [0.2, 0.1], "g.-" )
    plt.polar( [358*D2R,  2*D2R], [0.2, 0.1], "r.-" )
    plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
コード例 #25
0
ファイル: tube.py プロジェクト: neal-o-r/tube_map
def time_plot(centre, lats, tube_pd, dist, stations):
        # plot polar tube map of travel times

        centre = centre.upper() # upper case everything to match input data
        lat_c = float(lats['latitude'][lats['name'] == centre].values)
        lon_c = float(lats['longitude'][lats['name'] == centre].values)
	# get the lat lon of the centre station
	# and offset everything by this (put the centre at (0,0))
        lats['lat_off'] = lats['latitude']  - lat_c
        lats['lon_off'] = lats['longitude'] - lon_c

	# get the angle between (0,0)-(x,y) and the 'North'
        lats['angles'] = lats.apply(get_angle, axis=1)
	
        ind = stations.index(centre)
        # these are the min times to every station from this station
	times = dist[ind,:]
        angles=[]
        for station in stations:
		# collect the angles for the stations
                angles.append(float(lats['angles'][lats['name'] == station].values))

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='polar')

        for index, row in tube_pd.iterrows():
		# polar plot plot these
                # with r = travel time
		stat_to   = row['Station to']
                stat_from = row['Station from']	

                ang_to   = float(lats['angles'][lats['name']==stat_to].values)
                ang_from = float(lats['angles'][lats['name']==stat_from].values)
	
                r_to   = times[stations.index(stat_to)]
                r_from = times[stations.index(stat_from)]
        
               	plt.polar([ang_to,ang_from], [r_to,r_from], '-', color=row['Colour'])

        plt.title('Travel Time by Shortest Route from '+centre[0]+centre[1:].lower()+' (mins)')
	ax.set_xticklabels(['W', '', 'N', '', 'E', '', 'S', ''])
        plt.savefig('polar'+centre+'.eps', bbox_inches='tight')
コード例 #26
0
ファイル: obstacle.py プロジェクト: TNTECHARC/tntech-arc
	def startGraph( self ):
		import matplotlib
		matplotlib.use('GTKAgg')
		import gobject
		import matplotlib.pyplot as plt
		size = 6
		self.fig = plt.figure() 
		ax = self.fig.add_axes( [0,0,1,1], polar=True, axisbg='#d5de9c' )
		self.line, = plt.polar( [[6], [6]] )
		gobject.timeout_add( 5, self.client_.listen )
		plt.show()
コード例 #27
0
ファイル: jones.py プロジェクト: will-hossack/Python
    def polarPlot(self,key='r',points = 200):
        theta = [0.0]*(points + 1)
        intensity = [0.0]*(points + 1)
        delta = 360.0/points

        for i in range(points + 1):
            angle = math.radians(i*delta)
            theta[i] = angle
            intensity[i] = self.throughPolariser(angle)

        return polar(theta,intensity,key)
コード例 #28
0
ファイル: plotting_tools.py プロジェクト: jrminter/jmToolsPy3
def complexPolarPlot(a, color='#CC0000'):
    r"""Plot a list or vector of complex points as a polar plot.
    Defaults to red points.

    Parameters
    ----------
    a : a vector or list of complex points

    color : string '#CC0000', optionall
        a color string (Default red, '#CC0000')
    
    Returns
    -------
    fig   : a matplotlib Figure
    """
    from matplotlib import pyplot as plt
    import numpy as np
    for x in a:
        plt.polar(np.angle(x),np.abs(x), marker='.',color=color)
    fig = plt.gcf()
    return fig
コード例 #29
0
ファイル: crosstalk.py プロジェクト: Garyfallidis/trn
def subtract(n0,n1):
    plt.figure()
    needles2d = np.array([n0,n1,0.])
    f = [1.,0.,0.]
    sn0=signal2d(S0,f,b,d,needles2d,angles2d)
    f = [0.,1.,0.]
    sn1=signal2d(S0,f,b,d,needles2d,angles2d)
    #plt.polar(angles2d,s00,label='fibre at 0')
    #plt.polar(angles2d,s90,label='fibre at 90')
    plt.subplot(2,4,1,polar=True)
    plt.polar(angles2d,(sn0+sn1)/2.,label='mix')
    lines, labels = plt.rgrids( (20, 40, 60) )
    #plt.polar(angles2d,(s00-s90)/2.,label='diff fibres 0 and 90')
    for (i,theta) in enumerate(np.linspace(-np.pi/2,np.pi/2,7)):
        plt.subplot(2,4,i+2,polar=True)
        needles2d = np.array([0.,theta,0.])
        f = [0.,1.,0.]
        stheta=signal2d(S0,f,b,d,needles2d,angles2d)
        plt.polar(angles2d,(sn0+sn1)/2.-stheta,label=str(-180*theta/np.pi))
        lines, labels = plt.rgrids( (20, 40, 60) )
        plt.legend(loc='best')
    plt.suptitle('Subtraction from '+str(180*n0/np.pi)+'+'+str(180*n1/np.pi))
コード例 #30
0
ファイル: neuron.py プロジェクト: ohaas/cmn
    def plot_act(self):
        angle = ny.arange(0.0, 360, 45.0)
        neurons = [N(self.sigma).neuron_gauss(degree) for degree in angle]
        x3=ny.arange(0,2*ny.pi,2*ny.pi/361)
        ax = pp.subplot(111,polar=True)
        for i in ny.arange(0,len(angle)):
            ax.plot(x3,neurons[i], label='$neuron$ $%i$ $(\mu=%i\degree)$' %(i+1,i*45))
        pp.xlim(0,360)
        y=ny.arange(0,1.01,0.01)
        x=0.0*y

        # Shink current axis by 20%
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])


        pp.polar(x,y,color='blue', ls='--', lw=3, label='$Amplitude$\n$of$ $neuronal$\n$activation')
        pp.xlabel('Spacial orientation in degree with neuron %s=%.2f' % (u"\u03C3",self.sigma))
        pp.title('Neuronal tuning curves')

        # Put a legend to the right of the current axis
        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
コード例 #31
0
ファイル: mpl_radar.py プロジェクト: hakkuchan/summary
# 绘制雷达线
ax1.plot(theta,data1,'.--',label='data1')
ax1.fill(theta,data1,alpha=0.2)
ax1.plot(theta,data2,'.--',label='data2')
ax1.fill(theta,data2,alpha=0.2)
ax1.plot(theta,data3,'.--',label='data3')
ax1.fill(theta,data3,alpha=0.2)

plt.show()


""" 雷达图2(首尾闭合) """
labels = np.array(['a','b','c','d','e','f']) # 标签
dataLenth = 6 # 数据长度
data1 = np.random.randint(0,10,6) 
data2 = np.random.randint(0,10,6) # 数据

angles = np.linspace(0, 2*np.pi, dataLenth, endpoint=False) # 分割圆周长
data1 = np.concatenate((data1, [data1[0]])) # 闭合
data2 = np.concatenate((data2, [data2[0]])) # 闭合
angles = np.concatenate((angles, [angles[0]])) # 闭合

plt.polar(angles, data1, 'o-', linewidth=1) #做极坐标系
plt.fill(angles, data1, alpha=0.25)# 填充
plt.polar(angles, data2, 'o-', linewidth=1) #做极坐标系
plt.fill(angles, data2, alpha=0.25)# 填充

plt.thetagrids(angles * 180/np.pi, labels) # 设置网格、标签
plt.ylim(0,10)  # polar的极值设置为ylim

plt.show()
コード例 #32
0
ファイル: Polar.py プロジェクト: zyl6698/GeoPython
    def wulf(self, Width=1, Color='k'):
        """
        read the Excel, then draw the wulf net and Plot points, job done~
        """

        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)
        if ("csv" in self.name):
            raw = pd.read_csv(self.name)
        elif ("xlsx" in self.name):
            raw = pd.read_excel(self.name)

        Data = []
        Labels = []

        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))

        list1 = [self.eqan(x) for x in range(0, 90, 15)]
        list2 = [str(x) for x in range(0, 90, 15)]
        plt.rgrids(list1, list2)

        for i in range(len(raw)):
            Data.append([
                raw.at[i, "Name"], raw.at[i, "Dip"], raw.at[i, "Dip-Angle"],
                raw.at[i, "Color"], raw.at[i, "Width"], raw.at[i, "Alpha"],
                raw.at[i, "Label"]
            ])
            Dip = raw.at[i, "Dip"]
            Dip_Angle = raw.at[i, "Dip-Angle"]

            Label = raw.at[i, "Label"]
            if (Label not in Labels):
                Labels.append(Label)
            else:
                Label = ""

            Width = 1
            Color = 'red'
            Alpha = 0.8
            Marker = 'o'
            Size = 50

            Setting = [Width, Color, Alpha, Marker, Size]

            Width = raw.at[i, "Width"]
            Color = raw.at[i, "Color"]
            Alpha = raw.at[i, "Alpha"]
            Marker = raw.at[i, "Marker"]
            Size = raw.at[i, "Size"]

            if (Color not in Setting or Color != ""):
                Width = raw.at[i, "Width"]
                Color = raw.at[i, "Color"]
                Alpha = raw.at[i, "Alpha"]
                Marker = raw.at[i, "Marker"]
                Size = raw.at[i, "Size"]

                Setting = [Width, Color, Alpha, Marker, Size]
            r = np.arange(Dip - 90, Dip + 91, 1)
            BearR = [np.radians(-A + 90) for A in r]
            Line = (self.eqan(self.getangular(Dip_Angle, Dip, r)))

            plt.plot(BearR,
                     Line,
                     color=Color,
                     linewidth=Width,
                     alpha=Alpha,
                     label=Label)

        plt.thetagrids(range(360 + 90, 0 + 90, -30),
                       [str(x) for x in range(0, 360, 30)])
        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "Wulff.png", dpi=300)
        plt.savefig(self.name + "Wulff.svg", dpi=300)
        plt.show()
コード例 #33
0
ファイル: plotStuff.py プロジェクト: doug460/Fall2018
    # spacing here
    d = 1 / 2

    dTheta = 2 * pi / 720

    # get array factor from equation a coefficients
    af = []

    for indxTheta in range(0, 720):
        sum = 0
        theta = dTheta * indxTheta
        for n in range(-len(am) + 1, len(am)):
            if (n < 0):
                an = am[-n]
            else:
                an = am[n]
            sum += an * exp(1j * n * (2 * pi * d * cos(theta) - pi / 2))

        af.append(abs(sum))

    af = af / np.max(af)
    x = np.linspace(0, 2 * pi, num=720)

    plt.figure()
    plt.polar(x, af)
    plt.title('Array Factor')
    plt.xlabel(r'$\theta$')

    plt.show()
コード例 #34
0
plt.figure(5)
plt.plot(X,Y,linewidth=2)
plt.title('X-Y in wave frame',fontsize=12)
plt.xlabel('X',fontsize=12)
plt.ylabel('Y',fontsize=12)
plt.tick_params(labelsize=12)
plt.xlim(xmin=0)
plt.ylim(ymin=0)


# plot particle path time
plt.figure(6)
plt.plot(M,time,linewidth=2)  
plt.title('time vs M in wave frame',fontsize=12)
plt.xlabel('M',fontsize=12)
plt.ylabel('time',fontsize=12)
plt.tick_params(labelsize=12)
plt.xlim(xmin=1)
plt.ylim(ymin=0)
plt.ticklabel_format(style='sci',axis='y',scilimits=(0,0))

# plot particle path in alpha-radius coordinates
plt.figure(7)
plt.polar(alpha,R)  
plt.title('radius vs alpha in wave frame',fontsize=12)
plt.tick_params(labelsize=12)
plt.ylim(ymin=0)
plt.tight_layout()

plt.show()
コード例 #35
0
ファイル: b3.py プロジェクト: JaSchl/AP1718
import matplotlib.pyplot as plt
import numpy as np

U = 21.59140294
RC = 0.05926156
x,y,a = np.genfromtxt('Messwerte/b.txt', unpack=True)
b = 1000/x
z = a/b * 2*np.pi
z_plt = np.linspace(0, 2)

plt.polar(z, y/U, 'rx')
plt.polar(z_plt, np.cos(z_plt), 'k-')

# in matplotlibrc leider (noch) nicht möglich
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/b3.pdf')
コード例 #36
0
 def _map(self,
          param_x,
          param_y,
          data=None,
          method=np.mean,
          noplot=False,
          fig=None,
          ax=None,
          cax=None,
          bin_x=50,
          bin_y=50,
          cmap="jet",
          cm_min=None,
          cm_max=None,
          axescolor='w',
          polar=False,
          showmax=True,
          **kwargs):
     """
     Return a 2D histogram of the MC chain, showing the walker density per bin
     """
     if param_x not in self.paramstr or param_y not in self.paramstr:
         print(("You must choose param_x and param_y among %s" %
                self.paramstr))
         return
     x = self.chain[param_x]
     if hasattr(x, 'compressed'): x = x.compressed()
     y = self.chain[param_y]
     if hasattr(y, 'compressed'): y = y.compressed()
     if data is not None:
         H, bin_y, bin_x = binned_statistic_2d(y,
                                               x,
                                               data,
                                               method,
                                               bins=(bin_y, bin_x))[:3]
     else:
         H, bin_y, bin_x = np.histogram2d(y, x, bins=(bin_y, bin_x))
     H[np.isnan(H)] = np.nanmin(H)
     maxd = np.unravel_index(np.argmax(H), H.shape)
     if cm_min is None: cm_min = np.min(H)
     if cm_max is None: cm_max = np.max(H)
     cmap, norm, mappable = _core.colorbar(cmap=cmap,
                                           cm_min=cm_min,
                                           cm_max=cm_max)
     if noplot: return H, bin_y, bin_x, cmap, norm, mappable
     if not polar:
         if fig is None: fig = plt.figure()
         if ax is None: ax = fig.add_subplot(111)
         im = mplimageNonUniformImage(ax,
                                      cmap=cmap,
                                      norm=norm,
                                      interpolation='bilinear')
         arrbin_x = _core.bins_to_array(bin_x)
         arrbin_y = _core.bins_to_array(bin_y)
         im.set_data(arrbin_x, arrbin_y, H)
         ax.images.append(im)
         if showmax is True:
             ax.plot(arrbin_x[maxd[1]], arrbin_y[maxd[0]], '^w', ms=7)
         ax.set_xlim(bin_x[0], bin_x[-1])
         ax.set_xlabel(param_x)
         ax.set_ylim(bin_y[0], bin_y[-1])
         ax.set_ylabel(param_y)
     else:
         if ax is None:
             fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
         T, R = np.meshgrid(bin_x, bin_y)
         pax = ax.pcolormesh(T, R, H, cmap=cmap, norm=norm)
         ax.grid(True)
         if showmax is True: plt.polar(T[maxd], R[maxd], '^w', ms=7)
         ax.set_ylim(0, bin_y[-1])
         ax.set_title(param_x + ' vs ' + param_y)
     ax.grid(True, color=axescolor)
     ax.tick_params(axis='both', colors=axescolor)
     fig.colorbar(mappable, cax=cax)
コード例 #37
0
plt.xlabel('Crytocurrency')
plt.ylabel('Market capitalization (million USD)')
"""

# PIE CHART
"""
plt.figure(figsize=(4,4))
x = [0.31,0.3,0.14,0.1,0.15]
labels = ['nginx','Apache','IIS','Varnish','Others']
plt.pie(x,labels=labels, autopct='%1.1f%%', explode=[0.1] * 5)
plt.title('Web Server Usage Statistics')
# Las coordenadas aparecen al mover el mouse sobre la gráfica ...
plt.text(0.76,-1,'Dionisos!',fontsize = 10)
"""

# POLAR CHART
"""
theta = np.arange(0., 2., 1./180.) * np.pi
plt.polar(3 * theta, theta/6)
plt.polar(theta, np.cos(6 * theta))
plt.polar(theta, [1.2] * len(theta))
"""

plt.show()
"""
Matplotlib for Python Developers - Allen Yu, Claire Chung
Ed. Packt Publishing 2018
PENDIENTE
Initiating a figure with plt.figure()
"""
コード例 #38
0
ファイル: rhodonea.py プロジェクト: DiamondBond/labs
import numpy as np 
import matplotlib.pyplot as plt 
  
  
# setting the axes 
# projection as polar 
plt.axes(projection='polar') 
  
# setting the length 
# and number of petals 
a = 1
n = 6
  
# creating an array 
# containing the radian values 
rads = np.arange(0, 2 * np.pi, 0.001)  
  
# plotting the rose 
for rad in rads: 
    r = a * np.cos(n*rad) 
    plt.polar(rad, r, 'g.') 
   
# display the polar plot 
plt.show() 
コード例 #39
0
# las funciones en coordenadas polares tienen la forma $ r = f(\theta)$.
#
# En Matplotlib se dispone de la función `polar`, la cual traza una gráfica en coordenadas polares, dados como argumentos
# tanto la variable independiente $\theta$ como la función $r$. Enseguida vamos a ver cómo graficar la tan conocida
# rosa polar, cuya ecuación general está dada por:
#
# $$ r = a \cos\left( k\theta + \phi_0 \right) $$
#
# Implementando esto en Python, se tiene:

# In[20]:

theta = np.linspace(0, 2 * np.pi, 1000)
a, k, phi0 = 5, 7, 0
r = a * np.cos(k * theta + phi0)
plt.polar(theta, r, "r")

# Observe que la función `polar` funciona de manera bastante similar a `plot`, de hecho se le pueden pasar los mismos
# *keyword arguments* para personalizar el gráfico resultante.

# ## Gráficas de barras

# ## Gráficas de pastel
#
# Las gráficas de pastel (o de tarta, o gráficos circulares) nos sirven para representar porcentajes y proporciones. Matplotlib dispone de la función `pie`, cuya sintaxis depende del grado de personalización y control que se requiera sobre la gráfica de pastel a dibujar.
#
# Para ejemplificar el uso de esta función vamos a suponer que se tienen los siguientes datos sobre algunas personas que tienen cierta cantidad de manzanas en *su poder*:
#
# | Nombre | Manzanas |
# |-----|:----:|
# | Ana | 20 |
コード例 #40
0
ファイル: Polar.py プロジェクト: zyl6698/GeoPython
    def singlerose(self, Gap=10, Width=1, Name=['Dip'], Color=['red']):
        """
        draw the rose map of single sample with different items~
        """
        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)
        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))

        real_max = []

        for k in range(len(Name)):

            Data = []
            S = []
            R = []
            for i in range(len(self.raw)):
                S.append(self.raw.at[i, Name[k]])

            s = np.linspace(0, 360, 360 / Gap + 1)
            t = tuple(s.tolist())
            count = []

            for i in range(len(t)):
                tmp_count = 0
                for j in S:
                    if i < len(t) - 1:
                        if t[i] < j <= t[i + 1]:
                            tmp_count += 1
                count.append(tmp_count)

            count_max = max(count)
            real_max.append(count_max)

        maxuse = max(real_max)

        for k in range(len(Name)):
            Data = []
            S = []
            R = []
            for i in range(len(self.raw)):
                S.append(self.raw.at[i, Name[k]])

            s = np.linspace(0, 360, 360 / Gap + 1)
            t = tuple(s.tolist())
            count = []

            for i in range(len(t)):
                tmp_count = 0
                for j in S:
                    if i < len(t) - 1:
                        if t[i] < j <= t[i + 1]:
                            tmp_count += 1
                count.append(tmp_count)
            s = np.linspace(0, 360, 360 / Gap + 1)
            t = tuple(s.tolist())

            R_factor = 90 / maxuse

            for i in count:
                TMP = 90 - i * R_factor
                R.append(TMP)

            m, n = Polar().Trans(t, R)
            plt.plot(m, n, color=Color[k], linewidth=1, alpha=0.6, marker='')
            plt.fill(
                m,
                n,
                Color=Color[k],
                Alpha=0.6,
            )

        list1 = [self.eqar(x) for x in range(0, 90, 15)]
        list2 = [
            str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1) / 7))
        ]
        list2.reverse()
        plt.rgrids(list1, list2)

        plt.thetagrids(range(360 + 90, 0 + 90, -15),
                       [str(x) for x in range(0, 360, 15)])

        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "Rose.png", dpi=300)
        plt.savefig(self.name + "Rose.svg", dpi=300)
        plt.show()
コード例 #41
0
ファイル: Polar.py プロジェクト: zyl6698/GeoPython
    def multirose(self, Gap=10, Width=1, Name='Dip'):
        """
        draw the rose map of multiple samples~
        """

        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)

        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))

        real_max = []

        S = []
        R = []
        Color = []
        Label = []
        Whole = {}

        for i in range(len(self.raw)):
            S.append(self.raw.at[i, Name])

            if self.raw.at[
                    i, 'Color'] not in Color and self.raw.at[i, 'Color'] != '':
                Color.append(self.raw.at[i, 'Color'])
            if self.raw.at[
                    i, 'Label'] not in Label and self.raw.at[i, 'Label'] != '':
                Label.append(self.raw.at[i, 'Label'])

        Whole = ({k: [] for k in Label})

        WholeCount = ({k: [] for k in Label})

        for i in range(len(self.raw)):
            for k in Label:
                if self.raw.at[i, 'Label'] == k:
                    Whole[k].append(self.raw.at[i, Name])

        t = tuple(np.linspace(0, 360, 360 / Gap + 1).tolist())
        real_max = 0

        for j in range(len(Label)):

            for i in range(len(t)):
                tmp_count = 0
                for u in Whole[Label[j]]:
                    if i < len(t) - 1:
                        if t[i] < u <= t[i + 1]:
                            tmp_count += 1
                real_max = max(real_max, tmp_count)
                WholeCount[Label[j]].append(tmp_count)

        maxuse = real_max
        R_factor = 90 / maxuse

        for j in range(len(Label)):

            R = []
            for i in WholeCount[Label[j]]:
                TMP = 90 - i * R_factor
                R.append(TMP)

            m, n = Polar().Trans(t, R)
            plt.plot(m,
                     n,
                     color=Color[j],
                     linewidth=1,
                     alpha=0.6,
                     marker='',
                     label=Label[j])
            plt.fill(m, n, Color=Color[j], Alpha=0.6)

        list1 = [self.eqar(x) for x in range(0, 90, 15)]
        list2 = [
            str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1) / 7))
        ]
        list2.reverse()
        plt.rgrids(list1, list2)

        plt.thetagrids(range(360 + 90, 0 + 90, -15),
                       [str(x) for x in range(0, 360, 15)])

        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "MultiRose.png", dpi=300)
        plt.savefig(self.name + "MultiRose.svg", dpi=300)
        plt.show()
コード例 #42
0
def polar_plot(directivite, theta, title='Directivite de la configuration'):
    plt.polar(theta[1:-1], abs(directivite[1:-1]))
    plt.title(title)
    plt.show()
コード例 #43
0
ファイル: example4.py プロジェクト: ptracton/MachineLearning
#print('target:', target)

colormap = np.array(['blue', 'green', 'black'])
mplt.scatter(pandaData.a, pandaData.b, c=colormap[target.e])
mplt.scatter(pandaData.c, pandaData.d, c=colormap[target.e])
mplt.title("Title")
mplt.show()

mdl = KMeans(n_clusters=3, random_state=5).fit(target)
predict = mdl.predict
print("Predict: ", predict)
labels = mdl.labels_
print("Labels: ", labels)
cc = mdl.cluster_centers_
print("Cluster Centers", cc)
mplt.polar(cc, '-or')
mplt.show()

# decTree = DecisionTreeClassifier(criterion='entropy')
# print(decTree)
# fitDecTree = decTree.fit(pandaData, target)
# predict = decTree.predict([[0,1,2,2]])
# print("Predict", predict)
# out = export_graphviz(fitDecTree, out_file="output.dot")

# randomForest = RandomForestClassifier()
# fitRandomForest = randomForest.fit(pandaData, target)
# print("FI:", randomForest.feature_importances_)
# predict = randomForest.predict([[0,1,0,1]])
# print("Predict:", predict)
コード例 #44
0
ax1.set_theta_zero_location("N")

pullData = open('data.csv', 'r').read()
dataArray = pullData.split('\n')
thetadeg = []
rho = []

for eachLine in dataArray:
    if len(eachLine) > 1:
        x, y = eachLine.split(',')
        thetadeg.append(int(x))
        rho.append(float(y))

max_amp = max(rho)

thetarad = [x * (np.pi / 180) for x in thetadeg]

normalized_rho = [x - max_amp for x in rho]

min_rho = min(normalized_rho)

ax1.set_theta_direction(-1)

ax1.set_theta_zero_location("N")

plt.title("Radiation Pattern Normalized")

plt.polar(thetarad, normalized_rho, lw=3)

plt.savefig('RadiationPattern2D.png')
コード例 #45
0
def PAPolarPlot(dfData, theta, time=3e-3, amplitude=0.1, rticklabelangle=-45):
    """
	

	Parameters
	----------
	dfData : TYPE
		DESCRIPTION.
	angles : TYPE
		DESCRIPTION.
	amplitude : TYPE, optional
		DESCRIPTION. The default is 0.1.

	Returns
	-------
	fig : TYPE
		DESCRIPTION.
	ax : TYPE
		DESCRIPTION.
		
	Examples
	--------
	import johnspythonlibrary2 as jpl2
	shotno=104772
	sensor='PA2'
	dfPARaw,dfPA,dfPAMeta=jpl2.Hbtep.Get.magneticSensorData(shotno,sensor=sensor)

	dfData=dfPA.copy()*1e4
	theta=dfPAMeta.theta.values
	
	_plt.close('all')
# 	for time in np.linspace(3.5e-3,5.5e-3,51):
# 		print(time)
# 		fig,ax=PAPolarPlot(dfData.copy(),theta,time=time)
# 		ax.set_title('%d, %s, t=%.3f ms'%(shotno,sensor,time*1e3))

	time=4.06e-3
	fig,ax=PAPolarPlot(dfData.copy(),theta,time=time)
	ax.set_title('%d, %s, t=%.3f ms'%(shotno,sensor,time*1e3))
	jpl2.Plot.finalizeFigure(fig,figSize=[3,3])
	
	"""
    import numpy as np

    # fig,ax=_plt.subplots()
    _plt.figure()
    ax = _plt.subplot(111, projection='polar')

    theta_complete = _np.linspace(-_np.pi, _np.pi, 1000)
    r = np.zeros(theta_complete.shape)

    i = (dfData.index.get_loc(time, method='nearest'))
    r_pert = dfData.iloc[i].values
    # 	rmax=np.abs(r_pert).max()

    _plt.polar(theta_complete, r, linestyle='--', color='k', linewidth=2)
    _plt.polar(np.append(theta, theta[0]),
               np.append(r_pert, r_pert[0]),
               linestyle='-',
               color='r',
               linewidth=2)

    rticks = ax.get_yticks()
    rticklabels = ['%.2f G' % i for i in rticks]
    ax.set_yticklabels(rticklabels)
    # 	ax.set_xlabel('r')
    ax.set_rlabel_position(rticklabelangle)

    # 	ax.set_rmax(rmax*1.5)
    # 	ax.set_rmin(-rmax*1.5)

    fig = _plt.gcf()
    return fig, ax
コード例 #46
0
plt.show()

#Polar charts
"""
Polar plots use a completely different coordinate system, so we have dedicated a separate section to them.
A polar system is a two-dimensional coordinate system, where the position of a point is expressed in terms of a radius and an angle. 
This system is used where the relationship between two points is better expressed using those information.
The angular coordinate can be expressed either in radians or in degrees. Though, Matplotlib uses degrees.
The polar() Matplotlib function plots polar charts. Its parameters are two lists (of the same length)
theta for the angular coordinates and r for the radial coordinates. It's the corresponding function of plot() for polar charts, 
so it can take multiple theta and r, along with the formatting strings.
"""
theta = np.arange(
    0., 2., 1. / 180.
) * np.pi  # we define theta to be an array of 360 values, equally spaced between 0 and 2pi.
plt.polar(3 * theta, theta / 5)
#we draw a spiral.
plt.polar(theta, np.cos(
    4 *
    theta))  #we draw a polar rose, a pretty function that resembles a flower.
plt.polar(
    theta, [1.4] * len(theta)
)  #we draw a circular line. In a polar system, to draw a circle we just need to keep r constant
r = np.abs(np.sin(5 * theta) - 2. * np.cos(theta))
plt.polar(theta, r)
plt.thetagrids(range(45, 360, 90))
plt.rgrids(np.arange(0.2, 3.1, .7), angle=0)

plt.title("Polar chart")
plt.show()
コード例 #47
0
ファイル: void-test-plotter.py プロジェクト: wing-0/Exjobb
# power flow is larger than 95 % of the maximum value
maxang = np.zeros(len(voids))
for i in range(0, len(voids)):
    large = normS[:, i] > 0.95*normS[:, i].max()
    maxang[i] = np.mean(propang[large, i])

# Plot the angle where scattering is maximum for each void size
plt.figure()
plt.plot(voids, np.degrees(maxang), '.-')
plt.title('Mean angle of the 5 % with highest energy')
plt.xlabel('Size of void')
plt.ylabel('Propagation angle $\\phi$ [$^\\circ$]')

# Plot norm of the power flow for all PROPAGATION angles
plt.figure()
plt.polar(propang, normS/normS.max())
plt.title('Norm of the time avg. power flow (normalized)')
plt.xlabel('Propagation angle $\\phi$')
plt.ylabel('S/S$_{max}$')
plt.legend(voids, title='void')

# "Clean up" the data by removing all points with a norm of the power flow
# below 5 % of the mean
sig = normS > 0.05*normS.mean(axis=0)

plt.figure()

for i in range(0, len(voids)):
    plt.plot(np.degrees(propang[sig[:, i], i]), normS[sig[:, i], i])

plt.title('Norm of the time avg. power flow (normalized)\nValues below 5 %' +
コード例 #48
0
ファイル: TM.py プロジェクト: ram2091999/TL-Modes-Visualiser
def handleTM(st,
             modes=[0, 0],
             type_of_waveguide="Rectangular",
             A=10,
             B=5,
             R=5):
    if type_of_waveguide == "Rectangular":
        x = np.linspace(0, A, 101)
        y = np.linspace(0, B, 101)
        X, Y = np.meshgrid(x, y)
        M = int(modes[0])
        N = int(modes[1])
        par = TE_TM_Functions(M, N, A, B)
        if M == 0 and N == 0:
            st.error("m and n cannot be 0 at the same time")
            return
        u = np.cos(M * PI / A * X) * np.sin(N * PI / B * Y)
        v = np.sin(M * PI / A * X) * np.cos(N * PI / B * Y)
        fig, ax = plt.subplots()
        plt.streamplot(x, y, u, v, color="xkcd:azure")
        plt.axis("scaled")
        st.subheader("E field")
        plt.xlim(0, A)
        plt.ylim(0, B)
        st.pyplot(fig)

        u = np.sin(M * PI / A * X) * np.cos(N * PI / B * Y)
        v = -1 * np.cos(M * PI / A * X) * np.sin(N * PI / B * Y)
        fig, ax = plt.subplots()
        plt.streamplot(x, y, u, v, color="red")
        plt.axis("scaled")
        st.subheader("H field")
        plt.xlim(0, A)
        plt.ylim(0, B)
        st.pyplot(fig)
        st.subheader("Values")
        st.write(
            pd.DataFrame({
                "Parameter":
                ["Kc", "Fc", "Beta-g", "Vg", "Zin", "Zg", "lambda-g"],
                "Value": [
                    par.Kc(),
                    par.Fc(),
                    par.beta_g(),
                    par.v_G(),
                    par.Z_in(),
                    par.Z_G_TM(),
                    par.lambda_G(),
                ],
                "Unit": ["1/m", "Hz", "1/m", "m/s", "Ohm", "Ohm", "m"],
            }))

    else:
        r = np.linspace(0, R, 101)
        t = np.linspace(0, 2 * PI, 101)
        T, RAD = np.meshgrid(t, r)
        N = int(modes[0])
        P = int(modes[1])
        if P == 0:
            st.error("p cannot be 0!")
            return
        X = special.jn_zeros(N, P)
        U = -1 * special.jvp(N, X[-1].round(3) / R * RAD) * np.cos(N * T)
        V = special.jv(N, X[-1].round(3) / R * RAD) * np.sin(N * T)
        par = Circular_TE_TM_Functions(N, P, 2.3e-2)
        fig, ax = plt.subplots()

        plt.polar(2 * PI, R)
        plt.streamplot(T, RAD, V, U, color="xkcd:azure")
        plt.axis("scaled")
        st.subheader("E field")
        st.pyplot(fig)
        st.markdown("**Scale: 5units = 2.3 cm**")

        U = special.jv(N, X[-1].round(3) / R * RAD) * np.sin(N * T)
        V = special.jvp(N, X[-1].round(3) / R * RAD) * np.cos(N * T)

        fig, ax = plt.subplots()
        plt.polar(2 * PI, R)
        plt.streamplot(T, RAD, V, U, color="red")
        plt.axis("scaled")
        st.subheader("H field")
        st.pyplot(fig)
        st.markdown("**Scale: 5units = 2.3 cm**")

        st.subheader("Values")
        st.write(
            pd.DataFrame({
                "Parameter":
                ["Kc", "Fc", "Beta-g", "Vg", "Zin", "Zg", "lambda-g"],
                "Value": [
                    par.Kc_TM(),
                    par.Fc_TM(),
                    par.beta_g_TM(),
                    par.v_G_TM(),
                    par.Z_in(),
                    par.Z_G_TM(),
                    par.lambda_G_TM(),
                ],
                "Unit": ["1/m", "Hz", "1/m", "m/s", "Ohm", "Ohm", "m"],
            }))
コード例 #49
0
ファイル: pres.py プロジェクト: samer2point0/dissertation
def plotAtr(gName, a, FC='inH', slist=SetupList, FB=FuncList, FinH=FuncList):
    DF = pd.read_csv('./tests/' + gName + '_test.txt')

    tempslist = copy.deepcopy(slist)
    del tempslist[a]
    sslist = list(itertools.product(*tempslist))

    Fconst = FB if FC == 'B' else FinH
    Fchang = FinH if FC == 'B' else FB

    for setup in slist[a]:
        for i in range(len(Fconst)):
            size = 8
            fig = plt.figure(figsize=(size, size))
            assend = numpy.linspace(0, size, size)
            const = numpy.full((size, 0), size)

            colors = ['sienna', 'lime', 'g', 'c', 'y', 'm', 'r', 'b', 'grey']
            M = []
            for j, fch in enumerate(Fchang):
                L = []
                for z, x in enumerate(sslist):
                    x = list(x)
                    x.insert(a, setup)
                    b = i if FC == 'B' else j
                    h = j if FC == 'B' else i
                    c = str([FB[b], FinH[h], x[0], x[1], x[2]])
                    l = DF[c].dropna().tolist()
                    L.append(l)
                M.append(L)

            mini, maxi = [], []
            l = len(sslist)
            for j, fch in enumerate(Fchang):
                c = colors.pop()
                btheta = -3.1415 / 8
                for z, x in enumerate(sslist):
                    thetaInc = btheta + j * 3.1415 / len(Fchang) / 4
                    r = M[j][z]
                    theta = [
                        z * 3.1415 * 2 / l + thetaInc +
                        btheta * random.random() / len(Fchang) for x in r
                    ]
                    label = fch if z == 0 else None
                    plt.polar(theta,
                              r,
                              color=c,
                              marker='o',
                              ls=' ',
                              ms=3,
                              label=label)
                    plt.polar([3.1415 / l + z * 3.1415 / (l / 2)] * 2,
                              [0, 31000], '-k')
                    plt.polar([theta.pop()], [sum(r) / len(r)], 'xk')
                    maxi.append(max(r))

            maxi = max(maxi)
            plt.title('Graph ' + gName + ' with seedsize ' + str(setup) +
                      ' and ' + FC + ' functin ' + str(Fconst[i]))
            ax = fig.gca()
            ax.set_rmax(maxi + 100)
            ticks = [str(sslist[int(x)]) for x in range(l)]
            d = {'fontsize': 12, 'fontweight': 'bold'}
            ax.set_xticks([(x * 3.1415 / (l / 2)) for x in range(l)])
            ax.set_xticklabels(ticks, fontdict=d)
            plt.legend(loc='lower right')
            plt.show()
コード例 #50
0
        psiY = pi * sin(theta) * sin(phi)
        psiZ = pi * cos(theta) - pi
        afx = (1 + cos(psiX))
        afy = (1 + cos(psiY))
        if (abs(2 * sin(psiZ / 2)) > 0):
            afz = sin(psiZ) / (2 * sin(psiZ / 2))
        else:
            afz = 1

        ef = abs(cos(theta) * sin(phi) + cos(phi))
        af = afx * afy * afz * ef
        afXz.append(af)

    afXz = afXz / np.max(afXz)
    plt.figure()
    plt.polar(thetas, afXz)
    plt.title('AF along X-Z plane')
    plt.xlabel(r'$\theta$')
    plt.savefig('prob2_xz.png')

    # yz plane
    phi = pi / 2

    thetas = np.linspace(0, 2 * pi, 720)
    afYz = []
    for theta in thetas:
        psiX = pi * sin(theta) * cos(phi)
        psiY = pi * sin(theta) * sin(phi)
        psiZ = pi * cos(theta) - pi
        afx = (1 + cos(psiX))
        afy = (1 + cos(psiY))
コード例 #51
0
def main():
    # 散点图 scatter
    fig = plt.figure()
    # 表示散点图画在此区域内
    ax = fig.add_subplot(3, 3, 1)
    n = 102
    # 随机数
    X = np.random.normal(0, 1, n)
    Y = np.random.normal(0, 1, n)
    # 上色,Y除以X(颜色展示)
    T = np.arctan2(Y, X)
    # 指定显示范围
    # plt.axes([0.025, 0.025, 0.95, 0.95])
    # 用来画散点的,s表示大小,sise;c表示color
    ax.scatter(X, Y, s=75, c=T, alpha=.5)
    plt.xlim(-1.5, 1.5)
    plt.xticks([])
    plt.ylim(-1.5, 1.5)
    plt.yticks([])
    plt.axis()
    plt.title('scatter')
    plt.xlabel('x')
    plt.ylabel('y')

    # 柱状图 bar
    # fig.add_subplot(332)

    ax = fig.add_subplot(332)
    n = 10
    # 构造的数列,从0-9
    X = np.arange(n)
    # 随机数
    Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
    Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
    # 画出来,+Y1表示画在上面
    ax.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
    # 画出来,-Y2表示画在下面
    ax.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
    for x, y in zip(X, Y1):
        # Y1进行注释,x+0.4表示延x轴正方向0.4,y+0.05表示延y轴正方向移0.05,va='bottom'表示图在文字下面
        plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
    for x, y in zip(X, Y2):
        plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')

    # 饼图 Pie
    fig.add_subplot(333)
    n = 20
    # 全域的变量,为1
    Z = np.ones(n)
    # 最后一个变量设为2
    Z[-1] *= 2
    # Z表示每块儿的值,explode = Z * .05表示每个扇形离中心的距离,labels为显示的值,colors显示的颜色(以灰度形式)
    plt.pie(Z,
            explode=Z * .05,
            labels=['%.2f' % (i / float(n)) for i in range(n)],
            colors=['%f' % (i / float(n)) for i in range(n)])
    # 设为正的圆形
    plt.gca().set_aspect('equal')
    plt.xticks([]), plt.yticks([])

    # 极坐标 polar
    # fig.add_subplot(334)
    # 极坐标形式显示,polar=true
    fig.add_subplot(334, polar=True)
    n = 20
    theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / n)
    # 半径
    radii = 10 * np.random.rand(n)
    # plt.plot(theta, radii)
    plt.polar(theta, radii)

    # 热图 heatmap
    # colormap,上色
    from matplotlib import cm
    fig.add_subplot(335)
    data = np.random.rand(3, 3)
    cmap = cm.Blues
    # interpolation = 'nearest':离最近的差值
    map = plt.imshow(data,
                     cmap=cmap,
                     aspect='auto',
                     interpolation='nearest',
                     vmin=0,
                     vmax=1)
    # 3D图
    from mpl_toolkits.mplot3d import Axes3D
    ax = fig.add_subplot(336, projection='3d')
    # 坐标(1,1,3),size为100
    ax.scatter(1, 1, 3, s=100)

    # 热力图
    fig.add_subplot(313)

    def f(x, y):
        return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 - y**2)

    n = 256
    x = np.linspace(-3, 3, n)
    y = np.linspace(-3, 3, n)
    X, Y = np.meshgrid(x, y)
    # 热力图的函数
    plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
    plt.savefig("./fig.png")

    plt.show()
コード例 #52
0
ファイル: Polar.py プロジェクト: zyl6698/GeoPython
    def schmidt(self, Width=1, Color='k'):
        """
        read the Excel, then draw the schmidt net and Plot points, job done~
        """
        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)
        if ("csv" in self.name):
            raw = pd.read_csv(self.name)
        elif ("xlsx" in self.name):
            raw = pd.read_excel(self.name)

        Data = []
        Labels = []
        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))

        list1 = [self.eqar(x) for x in range(0, 90, 15)]
        list2 = [str(x) for x in range(0, 90, 15)]
        plt.rgrids(list1, list2)

        for i in range(len(raw)):
            Data.append([
                raw.at[i, "Name"], raw.at[i, "Dip"], raw.at[i, "Dip-Angle"],
                raw.at[i, "Color"], raw.at[i, "Width"], raw.at[i, "Alpha"],
                raw.at[i, "Marker"], raw.at[i, "Label"]
            ])
            Dip = raw.at[i, "Dip"]
            Dip_Angle = raw.at[i, "Dip-Angle"]

            Label = raw.at[i, "Label"]

            if (Label not in Labels):
                Labels.append(Label)
            else:
                Label = ""

            Width = 1
            Color = 'red'
            Alpha = 0.8
            Marker = 'o'
            Size = 50

            Setting = [Width, Color, Alpha, Marker, Size]

            Width = raw.at[i, "Width"]
            Color = raw.at[i, "Color"]
            Alpha = raw.at[i, "Alpha"]
            Marker = raw.at[i, "Marker"]
            Size = raw.at[i, "Size"]

            if (Color not in Setting or Color != ""):
                Width = raw.at[i, "Width"]
                Color = raw.at[i, "Color"]
                Alpha = raw.at[i, "Alpha"]
                Marker = raw.at[i, "Marker"]
                Size = raw.at[i, "Size"]

                Setting = [Width, Color, Alpha, Marker, Size]

            plt.scatter(np.radians(90 - Dip),
                        self.eqar(Dip_Angle),
                        marker=Marker,
                        s=Size,
                        color=Color,
                        alpha=Alpha,
                        label=Label,
                        edgecolors='black')

        # plt.plot(120, 30, color='K', linewidth=4, alpha=Alpha, marker='o')
        plt.thetagrids(range(360 + 90, 0 + 90, -30),
                       [str(x) for x in range(0, 360, 30)])

        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "Schmidt.png", dpi=300)
        plt.savefig(self.name + "Schmidt.svg", dpi=300)
        plt.show()
コード例 #53
0
    clientID=vrep.simxStart('127.0.0.1', 19997, True, True, 5000, 5) # Connect to V-REP

    if clientID != -1:
        print('Connected to remote API server')

        # enable the synchronous mode on the client:
        vrep.simxSynchronous(clientID, True)

        # start the simulation:
        vrep.simxStartSimulation(clientID,vrep.simx_opmode_blocking)
        vrep.simxSynchronousTrigger(clientID) # skip first timestep. LiDAR returns zero-size array at first timestep

        # get LiDAR measurement
        vrep.simxSynchronousTrigger(clientID)
        e, lrf = readLiDAR(clientID, 'measurement', opmode_blocking)

        # plot measurement
        theta = np.linspace(0, 2*np.pi, len(lrf))
        polarplot = plt.polar(theta, lrf)
        plt.show(polarplot)

        # stop the simulation:
        vrep.simxStopSimulation(clientID,vrep.simx_opmode_blocking)

        # Now close the connection to V-REP:
        vrep.simxFinish(clientID)
    else:
        print ('Failed connecting to remote API server')
    print ('Program ended')
コード例 #54
0
n = np.arange(0, numSamples, 1)
y1 = np.multiply(np.power(A, n), np.exp(1j * w1 * n))

# # plotting in 2-D, the real and imag in the same figure
# plt.figure(1)
# plt.plot(n, y1[0:numSamples].real,'r--o')
# plt.plot(n, y1[0:numSamples].imag,'g--o')
# plt.xlabel('sample index n'); plt.ylabel('y[n]')
# plt.title('Complex exponential (red=real) (green=imag)')
# plt.grid()
# plt.show()
#
# plotting in polar, understand what the spokes are
plt.figure(2)
for x in y1:
    plt.polar([0, np.angle(x)], [0, np.abs(x)], marker='o')
    #plt.polar([0,np.angle(x)],[0,np.abs(x)],marker='o')

plt.title('Polar plot showing phasors at n=0..N')
plt.show()

# plotting 3D complex plane
plt.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
reVal = y1[0:numSamples].real
imgVal = y1[0:numSamples].imag
#ax.plot(n,reVal, imgVal,  label='complex exponential phasor')
ax.scatter(n, reVal, imgVal, c='r', marker='o')
ax.set_xlabel('sample n')
ax.set_ylabel('real')
コード例 #55
0
    def onselect3(self, ymin, ymax):
        ymin = round(ymin, 3)
        ymax = round(ymax, 3)
        if ymin != ymax:
            self.lines = []  # 清空一下
            print('井段为:', ymin, '-', ymax)
            self.lines.append(ymin)
            self.lines.append(ymax)
        elif ymin == ymax:
            print('极值深度为:', ymax)
            self.lines.append(ymax)
            index = np.where(
                abs(self.log.data['DEPT'] -
                    ymax) <= float(abs(self.log.step) - 0.001))
            index = index[0][0]
            D01_value = self.log.data['D01'][index]
            D02_value = self.log.data['D02'][index]
            D03_value = self.log.data['D03'][index]
            D04_value = self.log.data['D04'][index]
            D05_value = self.log.data['D05'][index]
            D06_value = self.log.data['D06'][index]
            D07_value = self.log.data['D07'][index]
            D08_value = self.log.data['D08'][index]
            D09_value = self.log.data['D09'][index]
            D10_value = self.log.data['D10'][index]
            D11_value = self.log.data['D11'][index]
            D12_value = self.log.data['D12'][index]
            D13_value = self.log.data['D13'][index]
            D14_value = self.log.data['D14'][index]
            D15_value = self.log.data['D15'][index]
            D16_value = self.log.data['D16'][index]
            D17_value = self.log.data['D17'][index]
            D18_value = self.log.data['D18'][index]
            D19_value = self.log.data['D19'][index]
            D20_value = self.log.data['D20'][index]
            D21_value = self.log.data['D21'][index]
            D22_value = self.log.data['D22'][index]
            D23_value = self.log.data['D23'][index]
            D24_value = self.log.data['D24'][index]
            D25_value = self.log.data['D25'][index]
            D26_value = self.log.data['D26'][index]
            D27_value = self.log.data['D27'][index]
            D28_value = self.log.data['D28'][index]
            D29_value = self.log.data['D29'][index]
            D30_value = self.log.data['D30'][index]
            D31_value = self.log.data['D31'][index]
            D32_value = self.log.data['D32'][index]
            D33_value = self.log.data['D33'][index]
            D34_value = self.log.data['D34'][index]
            D35_value = self.log.data['D35'][index]
            D36_value = self.log.data['D36'][index]
            D37_value = self.log.data['D37'][index]
            D38_value = self.log.data['D38'][index]
            D39_value = self.log.data['D39'][index]
            D40_value = self.log.data['D40'][index]
            self.Min_value = self.log.data['IDMN'][index]
            self.Ave_value = self.log.data['IDAV'][index]
            self.Max_value = self.log.data['IDMX'][index]
            print(str(self.Min_value), ' ', str(self.Ave_value), ' ',
                  str(self.Max_value))
            if self.damage_Tag == 'Transformation':
                self.lines.append(round(self.Min_value, 3))
                self.lines.append(round(self.Ave_value, 3))
                self.lines.append(round(self.Max_value, 3))
                print(self.lines)
                # 保存list到文件
                self.lines_temp = pd.DataFrame(self.lines, columns=['value'])
                writer = pd.ExcelWriter('Transformation.xlsx')
                self.lines_temp.to_excel(writer, 'Sheet1')
                writer.save()
            elif self.damage_Tag == 'Penetration':
                All_Ders = [
                    D01_value, D02_value, D03_value, D04_value, D05_value,
                    D06_value, D07_value, D08_value, D09_value, D10_value,
                    D11_value, D12_value, D13_value, D14_value, D15_value,
                    D16_value, D17_value, D18_value, D19_value, D20_value,
                    D21_value, D22_value, D23_value, D24_value, D25_value,
                    D26_value, D27_value, D28_value, D29_value, D30_value,
                    D31_value, D32_value, D33_value, D34_value, D35_value,
                    D36_value, D37_value, D38_value, D39_value, D40_value
                ]
                All_Ders_Dict = {
                    'D01_value': D01_value,
                    'D02_value': D02_value,
                    'D03_value': D03_value,
                    'D04_value': D04_value,
                    'D05_value': D05_value,
                    'D06_value': D06_value,
                    'D07_value': D07_value,
                    'D08_value': D08_value,
                    'D09_value': D09_value,
                    'D10_value': D10_value,
                    'D11_value': D11_value,
                    'D12_value': D12_value,
                    'D13_value': D13_value,
                    'D14_value': D14_value,
                    'D15_value': D15_value,
                    'D16_value': D16_value,
                    'D17_value': D17_value,
                    'D18_value': D18_value,
                    'D19_value': D19_value,
                    'D20_value': D20_value,
                    'D21_value': D21_value,
                    'D22_value': D22_value,
                    'D23_value': D23_value,
                    'D24_value': D24_value,
                    'D25_value': D25_value,
                    'D26_value': D26_value,
                    'D27_value': D27_value,
                    'D28_value': D28_value,
                    'D29_value': D29_value,
                    'D30_value': D30_value,
                    'D31_value': D31_value,
                    'D32_value': D32_value,
                    'D33_value': D33_value,
                    'D34_value': D34_value,
                    'D35_value': D35_value,
                    'D36_value': D36_value,
                    'D37_value': D37_value,
                    'D38_value': D38_value,
                    'D39_value': D39_value,
                    'D40_value': D40_value,
                }
                FING_Max_value = max(All_Ders_Dict.values())
                FING_String = ''
                for key, value in All_Ders_Dict.items():
                    if value == FING_Max_value:
                        FING_String = key
                        self.lines.append(int(FING_String[1:3]))
                        value_3_digits = round(value, 3)  # 保留三位有效数字
                        self.lines.append(value_3_digits)
                        break

                # 求个平均值
                normal_Depth1 = float(
                    self.lines[0]) - 0.2  # 在井段开始深度上方0.2m处取一个正常的点进行读值
                normal_Depth2 = float(
                    self.lines[0]) - 0.4  # 在井段开始深度上方0.4m处取一个正常的点进行读值
                normal_Depth3 = float(
                    self.lines[0]) - 0.6  # 在井段开始深度上方0.6m处取一个正常的点进行读值
                normal_Depth4 = float(
                    self.lines[0]) - 0.8  # 在井段开始深度上方0.8m处取一个正常的点进行读值
                normal_Depth5 = float(
                    self.lines[0]) - 1.0  # 在井段开始深度上方1.0m处取一个正常的点进行读值

                index1 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth1) <= float(abs(self.log.step) - 0.001))
                index1 = index1[0][0]
                FING_value1 = self.log.data[FING_String[0:3]][index1]

                index2 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth2) <= float(abs(self.log.step) - 0.001))
                index2 = index2[0][0]
                FING_value2 = self.log.data[FING_String[0:3]][index2]

                index3 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth3) <= float(abs(self.log.step) - 0.001))
                index3 = index3[0][0]
                FING_value3 = self.log.data[FING_String[0:3]][index3]

                index4 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth4) <= float(abs(self.log.step) - 0.001))
                index4 = index4[0][0]
                FING_value4 = self.log.data[FING_String[0:3]][index4]

                index5 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth5) <= float(abs(self.log.step) - 0.001))
                index5 = index5[0][0]
                FING_value5 = self.log.data[FING_String[0:3]][index5]

                FING_value = round(
                    sum([
                        FING_value1, FING_value2, FING_value3, FING_value4,
                        FING_value5
                    ]) / 5.0, 3)

                self.lines.append(FING_value)
                self.lines.append(round(self.Min_value, 3))
                self.lines.append(round(self.Ave_value, 3))
                self.lines.append(round(self.Max_value, 3))
                print(self.lines)
                # 保存list到文件
                self.lines_temp = pd.DataFrame(self.lines, columns=['value'])
                writer = pd.ExcelWriter('Penetration.xlsx')
                self.lines_temp.to_excel(writer, 'Sheet1')
                writer.save()
            elif self.damage_Tag == 'Projection':
                All_Ders = [
                    D01_value, D02_value, D03_value, D04_value, D05_value,
                    D06_value, D07_value, D08_value, D09_value, D10_value,
                    D11_value, D12_value, D13_value, D14_value, D15_value,
                    D16_value, D17_value, D18_value, D19_value, D20_value,
                    D21_value, D22_value, D23_value, D24_value, D25_value,
                    D26_value, D27_value, D28_value, D29_value, D30_value,
                    D31_value, D32_value, D33_value, D34_value, D35_value,
                    D36_value, D37_value, D38_value, D39_value, D40_value
                ]
                All_Ders_Dict = {
                    'D01_value': D01_value,
                    'D02_value': D02_value,
                    'D03_value': D03_value,
                    'D04_value': D04_value,
                    'D05_value': D05_value,
                    'D06_value': D06_value,
                    'D07_value': D07_value,
                    'D08_value': D08_value,
                    'D09_value': D09_value,
                    'D10_value': D10_value,
                    'D11_value': D11_value,
                    'D12_value': D12_value,
                    'D13_value': D13_value,
                    'D14_value': D14_value,
                    'D15_value': D15_value,
                    'D16_value': D16_value,
                    'D17_value': D17_value,
                    'D18_value': D18_value,
                    'D19_value': D19_value,
                    'D20_value': D20_value,
                    'D21_value': D21_value,
                    'D22_value': D22_value,
                    'D23_value': D23_value,
                    'D24_value': D24_value,
                    'D25_value': D25_value,
                    'D26_value': D26_value,
                    'D27_value': D27_value,
                    'D28_value': D28_value,
                    'D29_value': D29_value,
                    'D30_value': D30_value,
                    'D31_value': D31_value,
                    'D32_value': D32_value,
                    'D33_value': D33_value,
                    'D34_value': D34_value,
                    'D35_value': D35_value,
                    'D36_value': D36_value,
                    'D37_value': D37_value,
                    'D38_value': D38_value,
                    'D39_value': D39_value,
                    'D40_value': D40_value,
                }
                FING_Min_value = min(All_Ders_Dict.values())
                FING_String = ''
                for key, value in All_Ders_Dict.items():
                    if value == FING_Min_value:
                        FING_String = key
                        self.lines.append(int(FING_String[1:3]))
                        value_3_digits = round(value, 3)  # 保留三位有效数字
                        self.lines.append(value_3_digits)
                        break

                # 求个平均值
                normal_Depth1 = float(
                    self.lines[0]) - 0.2  # 在井段开始深度上方0.2m处取一个正常的点进行读值
                normal_Depth2 = float(
                    self.lines[0]) - 0.4  # 在井段开始深度上方0.4m处取一个正常的点进行读值
                normal_Depth3 = float(
                    self.lines[0]) - 0.6  # 在井段开始深度上方0.6m处取一个正常的点进行读值
                normal_Depth4 = float(
                    self.lines[0]) - 0.8  # 在井段开始深度上方0.8m处取一个正常的点进行读值
                normal_Depth5 = float(
                    self.lines[0]) - 1.0  # 在井段开始深度上方1.0m处取一个正常的点进行读值

                index1 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth1) <= float(abs(self.log.step) - 0.001))
                index1 = index1[0][0]
                FING_value1 = self.log.data[FING_String[0:3]][index1]

                index2 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth2) <= float(abs(self.log.step) - 0.001))
                index2 = index2[0][0]
                FING_value2 = self.log.data[FING_String[0:3]][index2]

                index3 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth3) <= float(abs(self.log.step) - 0.001))
                index3 = index3[0][0]
                FING_value3 = self.log.data[FING_String[0:3]][index3]

                index4 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth4) <= float(abs(self.log.step) - 0.001))
                index4 = index4[0][0]
                FING_value4 = self.log.data[FING_String[0:3]][index4]

                index5 = np.where(
                    abs(self.log.data['DEPT'] -
                        normal_Depth5) <= float(abs(self.log.step) - 0.001))
                index5 = index5[0][0]
                FING_value5 = self.log.data[FING_String[0:3]][index5]

                FING_value = round(
                    sum([
                        FING_value1, FING_value2, FING_value3, FING_value4,
                        FING_value5
                    ]) / 5.0, 3)

                self.lines.append(FING_value)
                self.lines.append(round(self.Min_value, 3))
                self.lines.append(round(self.Ave_value, 3))
                self.lines.append(round(self.Max_value, 3))
                print(self.lines)
                # 保存list到文件
                self.lines_temp = pd.DataFrame(self.lines, columns=['value'])
                writer = pd.ExcelWriter('Projection.xlsx')
                self.lines_temp.to_excel(writer, 'Sheet1')
                writer.save()

            self.fig2 = plt.figure('截面图')
            # 设置下面所需要的参数
            barSlices1 = 40
            barSlices2 = 100

            # theta指每个标记所在射线与极径的夹角,下面表示均分角度
            theta1 = np.linspace(0.0, 2 * np.pi, barSlices1, endpoint=False)
            theta2 = np.linspace(0.0, 2 * np.pi, barSlices2, endpoint=False)

            # # r表示点距离圆心的距离,np.random.rand(barSlices)表示返回返回服从“0-1”均匀分布的随机样本值
            # r = 2 * np.random.rand(barSlices) + 50
            r = [
                D01_value, D02_value, D03_value, D04_value, D05_value,
                D06_value, D07_value, D08_value, D09_value, D10_value,
                D11_value, D12_value, D13_value, D14_value, D15_value,
                D16_value, D17_value, D18_value, D19_value, D20_value,
                D21_value, D22_value, D23_value, D24_value, D25_value,
                D26_value, D27_value, D28_value, D29_value, D30_value,
                D31_value, D32_value, D33_value, D34_value, D35_value,
                D36_value, D37_value, D38_value, D39_value, D40_value
            ]

            # 网上搜的方法,不知道怎么就可以闭合了(黑人问号)
            r = np.concatenate((r, [r[0]]))  # 闭合
            theta1 = np.concatenate((theta1, [theta1[0]]))  # 闭合
            theta2 = np.concatenate((theta2, [theta2[0]]))  # 闭合

            inside_radius = [float(self.inner_diameter.value) / 2] * barSlices2
            outside_radius = [float(self.outer_diameter.value) / 2
                              ] * barSlices2

            inside_radius = np.concatenate(
                (inside_radius, [inside_radius[0]]))  # 闭合
            outside_radius = np.concatenate(
                (outside_radius, [outside_radius[0]]))  # 闭合

            # 绘图之前先清理一下
            plt.clf()
            # polar表示绘制极坐标图,颜色,线宽,标志点样式
            plt.polar(theta1,
                      r,
                      color="blue",
                      linewidth=1,
                      marker="",
                      mfc="b",
                      ms=10)
            plt.gca().set_theta_zero_location('N')
            # plt.gca().set_rlim(0, 57.15)  # 设置显示的极径范围
            plt.gca().set_rlim(0, float(self.outer_diameter.value) / 2)
            plt.gca().fill(theta1, r, facecolor='w', alpha=0.2)  # 填充颜色
            plt.gca().fill_between(theta2,
                                   outside_radius,
                                   inside_radius,
                                   facecolor='cyan',
                                   alpha=0.8)  # 填充之间颜色
            plt.gca().patch.set_facecolor('1')
            plt.gca().set_rgrids(np.arange(0, 100, 100))

            # label = np.array([j for j in range(1, 25)])  # 定义标签
            # plt.gca().set_thetagrids(np.arange(0, 360, 15), label)
            plt.gca().set_thetagrids(np.arange(0, 360, 360))

            text_show = ''.join(['Depth:', str(ymax), 'm\nOD: ', str(self.outer_diameter.value), 'mm\nID: ', \
                                 str(self.inner_diameter.value),'mm\nWT: ', str(self.thickness.value), 'mm'])
            plt.text(7 * np.pi / 4, 90, text_show)
            # 绘图展示
            plt.show()
コード例 #56
0
plt.title('Vertical Bar Chart')

# Horizontal Bar
plt.subplot(3, 3, 6)
profit = [800, 1200, 1300, 1600, 1600, 900, 1900, 900, 1600, 1550, 2100, 2300]
months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
    'Nov', 'Dec'
]
plt.barh(months, profit)
plt.xticks(fontsize=5, rotation=90)
plt.yticks(fontsize=6)
plt.xlabel('Month')
plt.ylabel('Profit')
plt.title('Vertical Bar Chart')

# Polar
from math import pi

plt.subplot(3, 3, 7, projection='polar')
radius = [0, 1, 2, 3, 4, 5]
theta = [0, pi / 6, pi / 3, pi / 2, 2 * pi / 3, 5 * pi / 6]
plt.polar(theta, radius)
plt.xticks(fontsize=5)
plt.yticks(range(6), fontsize=5)
plt.title('Polar Plot')

# Adjust the spacing between subplots
plt.subplots_adjust(hspace=1.25, wspace=0.75)
plt.show()
コード例 #57
0
sol_M = integrate.solve_ivp(f_M, t_span, [u0_M, kM], t_eval=t_eval)
sol_P = integrate.solve_ivp(f_P, t_span, [u0_P, kp], t_eval=t_eval)

r_M = schwarzR / sol_M.y[0]
r_P = schwarzR / sol_P.y[0]

#_______________ZERO MASS__________________________________
plt.plot(sol_P.t, r_P, c='r', lw='1', label='Particle')
plt.title('Motion of particle of zero mass')
plt.xlabel('Angular position on the equitorial plane')
plt.ylabel('Position of zero mass particle from centre of black hole')
plt.axhline(schwarzR, c='grey', label='Schwarzcschild Radius')
plt.legend()
plt.show()

plt.polar(sol_P.t, r_P, c="r", lw="1")
plt.title('Motion of particle of zero mass')
plt.fill(t_eval, np.full_like(t_eval, schwarzR), c="grey")
plt.grid(b=None, which="Major", axis="y")
plt.yticks([])
plt.show()

#_______________NON-ZERO MASS___________________________
plt.plot(sol_M.t, r_M, c='r', lw='1', label='Particle')
plt.title('Motion of particle of non-zero mass')
plt.axhline(schwarzR, c='grey', label='Schwarzschild Radius')
plt.xlabel('Angular position on the equitorial plane')
plt.ylabel('Position of non-zero mass particle from centre of black hole')
plt.legend()
plt.show()
コード例 #58
0
def scan_callback(msg):
    range_ahead = msg.ranges[len(msg.ranges) / 2]
    print("range ahead: %0.1f" % range_ahead)
    # r = np.array(msg.ranges)
    # print(r.shape)
    plt.polar(theta, msg.ranges)
コード例 #59
0
ファイル: I-TP10.py プロジェクト: Costadoat/Informatique
fig21=plt.figure(num=21)
plt.plot(les_x,les_y)
plt.grid()
plt.axis('equal')
titre = 'Trajectoire calculs euler polaires. \n dt ='\
+str(dt)+'\n x0='+str(x0)+' ; y0='+str(0)+' ; vx0='+str(0)\
+' ; vy0='+str(vy0)+'\n ecart en energie :'+'%.2f' % ecart+' %'
plt.title(titre)
plt.xlabel('$x$')
plt.ylabel('$y$')
#fig21.savefig('PolaireSimple1.eps',dpi=fig21.dpi)
plt.show()
plt.close()

fig22=plt.figure(num=22)
plt.polar(les_theta,les_r)
titre = 'Trajectoire calculs euler polaires ; pas dt ='\
+str(dt)+'\n x0='+str(x0)+' ; y0='+str(0)+' ; vx0='+str(0)\
+' ; vy0='+str(vy0)+'\n ecart en energie :'+'%.2f' % ecart+' %'
plt.title(titre)
#fig22.savefig('PolaireSimple2.eps',dpi=fig22.dpi)
plt.show()
plt.close()

#==============================================================================
# II - Comparaison entre methodes Euler et Leap-frog CI quelconques
#==============================================================================
#==============================================================================
# Conditions initiales et constantes
#==============================================================================
コード例 #60
0
         linestyle='--',
         marker='P',
         color='black',
         markersize=25,
         markerfacecolor='red',
         markeredgecolor='cyan',
         markeredgewidth=5)

################################
plt.plot(x, y)
plt.scatter(x, y)
plt.hist(x, y)
plt.hist2d(x, y, bins=10)
plt.bar(x, y)
plt.boxplot(x, y)
plt.polar(x, y)

# Heatmap
# num = np.random.random((4,4))
# plt.imshow(num, cmap = 'heat', interpolation = 'nearest')
# plt.show()

##### OOP (object oreiented plot)
x = np.linspace(1, 50, 20)
y = np.random.randint(1, 50, 20)
y = np.sort(y)

fig = plt.figure()
axes = fig.add_axes([0, 0, 1, 1])
axes1 = fig.add_axes([0.4, 0.2, 0.4, 0.7])
axes.set_xlabel('Master X-Axis')