Exemple #1
0
    def set_defaults(self):
        fontsize = {}
        for key, val in self.configdict.items():
            if 'font' in key:
                fontsize[key] = val
            else:
                setattr(self, key, val)

        self.zoom_lims = []
        self.added_texts = []
        self.scatter_xdata = None
        self.scatter_ydata = None
        self.scatter_mask = None
        self.margins = None
        self.mpl_legend  = None
        self.axes_traces = {}

        # preload some traces
        self.traces = []
        self.reset_lines()

        f0 =  FontProperties()
        self.labelfont = f0.copy()
        self.titlefont = f0.copy()
        self.legendfont = f0.copy()
        self.legendfont.set_size(fontsize['legendfont'])
        self.labelfont.set_size(fontsize['labelfont'])
        self.titlefont.set_size(fontsize['titlefont'])
        self.set_theme()
Exemple #2
0
def plot_image(image,title):
    print title
    maxi = np.amax(image)
    med = np.median(image)
    fig = plt.figure(figsize=(10,10))
    font0 = FontProperties()
    font = font0.copy()
    font.set_weight('bold')
    ax = fig.add_subplot(1,1,1)
    ax.tick_params(axis='x', labelsize=25)
    ax.tick_params(axis='y', labelsize=25)
#    image = filters.gaussian_filter(Q_image[149:549,149:549],1)
    img1 = ax.imshow(np.log10(np.abs(image)), origin='lower', vmin = np.log10(np.abs(med)), vmax = np.log10(np.abs(maxi)))
    fig.colorbar(img1, ax=ax)
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    plt.savefig(title + 'log10.png', dpi = 600)
    plt.close()
    fig = plt.figure(figsize=(10,10))
    font0 = FontProperties()
    font = font0.copy()
    font.set_weight('bold')
    ax = fig.add_subplot(1,1,1)
    ax.tick_params(axis='x', labelsize=25)
    ax.tick_params(axis='y', labelsize=25)
#    image = filters.gaussian_filter(Q_image[149:549,149:549],1)
    img1 = ax.imshow(np.abs(image), origin='lower', vmin = np.abs(med), vmax = np.abs(maxi))
    fig.colorbar(img1, ax=ax)
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    plt.savefig(title + '.png', dpi = 600)
    plt.close()
def create_results_figure(model_names, method_names, values, filename):
    results_table = np.array(values).transpose()

    n_models = results_table.shape[0]
    n_methods = results_table.shape[1]

    index = np.arange(n_methods)
    cmap = plt.get_cmap('tab20')
    x = np.linspace(0.0, 1.0, 100)

    font0 = FontProperties()
    font0.set_weight('medium')
    font0.set_size('medium')
    font1 = font0.copy()
    font1.set_size('x-large')
    font2 = font0.copy()
    font2.set_size('xx-large')

    dpi = 70
    step = (1.0 / n_models) * 0.9
    xmax = 100000.0
    plt.figure(figsize=(1000 / dpi, 2500 / dpi), dpi=dpi)
    for i in range(n_models):
        color = cmap(i / n_models)
        ax = plt.barh(index - 0.35 + i * step,
                      results_table[i],
                      step,
                      alpha=1.0,
                      color=color,
                      label=model_names[i])
        rects = ax.patches

        for j in range(len(rects)):
            rect = rects[j]
            read_time = results_table[i][j]
            if read_time == 0:
                label = 'N/A'
            else:
                label = '  %-7.2f' % (results_table[i][j])
            w = min(rect.get_width(), xmax - 1500)
            h = rect.get_y() + rect.get_height() * 0.45
            if w == 0:
                w = 0.32

    plt.ylabel('Library', fontproperties=font1)
    plt.xlabel('Time (log ms)', fontproperties=font1)
    plt.legend(bbox_to_anchor=(1.1, 1.0))
    plt.xscale('log')
    plt.xlim(0.3, xmax)
    plt.yticks(np.arange(n_methods), method_names)
    plt.tight_layout()
    # plt.show()
    plt.savefig(filename, dpi=dpi)
Exemple #4
0
    def set_defaults(self):
        self.zoom_x = 0
        self.zoom_y = 0
        self.zoom_init = (0, 1)
        self.zoom_lims = []
        self.viewpad = 2.5
        self.title  = ' '
        self.xscale = 'linear'
        self.yscale = 'linear'
        self.xlabel = ' '
        self.ylabel = ' '
        self.y2label = ' '
        self.added_texts = []
        self.plot_type = 'lineplot'
        self.scatter_size = 30
        self.scatter_normalcolor = 'blue'
        self.scatter_normaledge  = 'blue'
        self.scatter_selectcolor = 'red'
        self.scatter_selectedge  = 'red'
        self.scatter_xdata = None
        self.scatter_ydata = None
        self.scatter_mask = None

        self.margins = None
        self.auto_margins = True
        self.legend_loc    = 'best'
        self.legend_onaxis = 'on plot'
        self.mpl_legend  = None
        self.show_grid   = True
        self.draggable_legend = False
        self.hidewith_legend = True
        self.show_legend = False
        self.show_legend_frame = False
        self.axes_style = 'box'

        f0 =  FontProperties()
        self.labelfont = f0.copy()
        self.titlefont = f0.copy()
        self.legendfont = f0.copy()
        self.legendfont.set_size(7)
        self.labelfont.set_size(9)
        self.titlefont.set_size(10)
        self.color_themes = ColorThemes
        self.color_theme = 'light'
        self.set_color_theme(self.color_theme)

        # preload some traces
        self.ntrace = 0
        self.lines  = [None]*200
        self.traces = []
        self.reset_trace_properties()
Exemple #5
0
    def set_defaults(self):
        self.zoom_x = 0
        self.zoom_y = 0
        self.zoom_init = (0, 1)
        self.zoom_lims = []
        self.viewpad = 2.5
        self.title = ' '
        self.xscale = 'linear'
        self.yscale = 'linear'
        self.xlabel = ' '
        self.ylabel = ' '
        self.y2label = ' '
        self.added_texts = []
        self.plot_type = 'lineplot'
        self.scatter_size = 30
        self.scatter_normalcolor = 'blue'
        self.scatter_normaledge = 'blue'
        self.scatter_selectcolor = 'red'
        self.scatter_selectedge = 'red'
        self.scatter_xdata = None
        self.scatter_ydata = None
        self.scatter_mask = None

        self.margins = None
        self.auto_margins = True
        self.legend_loc = 'best'
        self.legend_onaxis = 'on plot'
        self.mpl_legend = None
        self.show_grid = True
        self.draggable_legend = False
        self.hidewith_legend = True
        self.show_legend = False
        self.show_legend_frame = False
        self.axes_style = 'box'

        f0 = FontProperties()
        self.labelfont = f0.copy()
        self.titlefont = f0.copy()
        self.legendfont = f0.copy()
        self.legendfont.set_size(7)
        self.labelfont.set_size(9)
        self.titlefont.set_size(10)
        self.color_themes = ColorThemes
        self.color_theme = 'light'
        self.set_color_theme(self.color_theme)

        # preload some traces
        self.ntrace = 0
        self.lines = [None] * 200
        self.traces = []
        self.reset_trace_properties()
def createFont(family=None,
               style=None,
               variant=None,
               weight=None,
               stretch=None,
               size=None,
               fontFilePathName=None):
    """Returns a Font Object for text in Matplotlib."""

    #### Copy Global Font Properties ####
    if fontFilePathName:
        try:
            font0 = FontProperties(fname=fontFilePathName)
        except:
            font0 = FontProperties()
    else:
        font0 = FontProperties()
    font = font0.copy()

    #### Adjust Based on Arguments ####
    if family != None:
        font.set_family(family)
    if style != None:
        font.set_style(style)
    if variant != None:
        font.set_variant(variant)
    if weight != None:
        font.set_weight(weight)
    if stretch != None:
        font.set_stretch(stretch)
    if size != None:
        font.set_size(size)

    return font
def CalibrationENC(calibration_filename):
    # Read data fron the calibration curve dataset
    C, e_C, noise_rms, d_noise_rms, fall_time, d_fall_time, amplitude, d_amplitude = LoadCalibrationFile(calibration_filename)

    noise_rms = noise_rms / 1000. # convert form \muV to mV
    d_noise_rms = d_noise_rms / 1000.

    ENC = (noise_rms/amplitude) * (C * 20.0) * pow(10,-15) / (1.602 * pow(10,-19) ) #pF * mV = 10^-12 * 10^-3 = 10^-15 C / 10^-19 C = 10^4 electrons
    d_ENC = np.zeros([len(ENC)])
    for i in range(len(ENC)):
        d_ENC[i] = sqrt( d_noise_rms[i]*d_noise_rms[i]*(C[i] * 20.0/amplitude[i])*(C[i] * 20.0/amplitude[i])  +  d_amplitude[i]*d_amplitude[i]*((noise_rms[i]/(amplitude[i]*amplitude[i])) * (C[i] * 20.0))*((noise_rms[i]/(amplitude[i]*amplitude[i])) * (C[i] * 20.0))    )
    
    d_ENC = d_ENC * pow(10,-15) / (1.602 * pow(10,-19) ) # conversted to # of electrons

    calib_curve = TGraphErrors(len(ENC), array('d', C[:-1].tolist()), array('d', ENC.tolist()), array('d', e_C.tolist()), array('d', d_ENC) )

    # Construct the fit with a 1st and 2nd order polynomial
    fit_curve = TF1('fit_curve','[1]*x + [0]',0.,110.)
    fit_curve2 = TF1('fit_curve2','[0]*x*x + [1]*x + [2]',0.,110.)

    # Fit the calibration curve
    calib_curve.Fit(fit_curve,'R')
    calib_curve.Fit(fit_curve2, 'R')

    lin_par0   = fit_curve.GetParameter(0)
    lin_e_par0 = fit_curve.GetParError(0)
    lin_par1   = fit_curve.GetParameter(1)
    lin_e_par1 = fit_curve.GetParError(1)

    xx = np.linspace(0., 105, 1000)
    yy = [fit_curve.Eval(x) for x in xx]
    yy2 = [fit_curve2.Eval(x) for x in xx]

    par = [lin_par0, lin_par1]
    l = 'fit pol1 $p_0$: {:.3g} $p_1$: {:.3g}'.format(*par)


    # Plot the calibration curve with matplotlib
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('x-large')

    fig, ax = plt.subplots()
    ax.set_xlabel('C [pF]')
    ax.set_ylabel('ENC [# of electrons]')
    ax.errorbar(C, ENC, d_ENC, marker='o', color='k', linestyle='None', label='Data')
    ax.plot(xx, yy, color='r', label=l)
    ax.plot(xx, yy2, color='g', label='fit pol2')
    ax.text(0.05,0.65, 'Group 1', verticalalignment='bottom', horizontalalignment='left',
                fontproperties=font, transform=ax.transAxes)
    ax.legend(loc='upper left', numpoints=1)
    plt.grid()
    #plt.show()
    fig.savefig('../graphics/calibrationENC_diode.pdf')
    plt.close(fig)
    plt.clf()

    return lin_par0, lin_e_par0, lin_par1, lin_e_par1
Exemple #8
0
def draw_output_element(out_name, out_value, ax):
    # Add output value
    x, y = np.array([[out_value, out_value], [0, 0.24]])
    line = lines.Line2D(x, y, lw=2., color='#F2F2F2')
    line.set_clip_on(False)
    ax.add_line(line)

    font0 = FontProperties()
    font = font0.copy()
    font.set_weight('bold')
    text_out_val = plt.text(out_value,
                            0.25,
                            '{0:.2f}'.format(out_value),
                            fontproperties=font,
                            fontsize=14,
                            horizontalalignment='center')
    text_out_val.set_bbox(dict(facecolor='white', edgecolor='white'))

    text_out_val = plt.text(out_value,
                            0.33,
                            out_name,
                            fontsize=12,
                            alpha=0.5,
                            horizontalalignment='center')
    text_out_val.set_bbox(dict(facecolor='white', edgecolor='white'))
def createFont(family = None, style = None, variant = None, weight = None, 
               stretch = None, size = None, fontFilePathName = None):
    """Returns a Font Object for text in Matplotlib."""

    #### Copy Global Font Properties ####
    if fontFilePathName:
        try:
            font0 = FontProperties(fname = fontFilePathName)
        except:
            font0 = FontProperties()
    else:
        font0 = FontProperties()
    font = font0.copy()

    #### Adjust Based on Arguments ####
    if family != None:
        font.set_family(family)
    if style != None:
        font.set_style(style)
    if variant != None:
        font.set_variant(variant)
    if weight != None:
        font.set_weight(weight)
    if stretch != None:
        font.set_stretch(stretch)
    if size != None:
        font.set_size(size)

    return font
Exemple #10
0
    def __init__(self,Model_suite,**input_parameters):
        
        self.working_directory = '.'
        self.station_listfile = None
        self.station_xyfile = None
        self.Model_suite = Model_suite
        self.modeltype = 'model'
        self.fig_width = 1.
        self.ax_width = 0.03
        self.ax_height = 0.8
        self.ax_bottom = 0.1
        self.plot_spacing = 0.02
        self.ylim = [6,0]
        self.title_type = 'single'
        self.titles = {'minmax':'Minimum and maximum resistivity, $\Omega m$',
                       'aniso':'Anisotropy in resistivity',# (maximum/minimum resistivity)
                       'strike':'Strike angle of minimum resistivity'}#, $^\circ$
        self.xlim = {'minmax':[0.1,1000],
                     'aniso':[0,20],
                     'strike':[0,180]}
        self.fonttype = 'serif'
        self.label_fontsize = 8
        self.title_fontsize = 12
                     
        for key in input_parameters.keys():
            setattr(self,key,input_parameters[key])

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font
            
        self.working_directory = os.path.abspath(self.working_directory)
Exemple #11
0
def drawtable(data, rows, columns, title, folder='Table', rowname='',fmt='{:.2f}'):
	nrows = len(rows)
	ncols = len(columns)
	fig, ax = plt.subplots(figsize=(ncols+2,nrows+2))
	ax.set_axis_off()
	rowlc='#F0F0F0'
	collc='#F0F0F0'
	cellc='#FFFFFF'
	ecol='#0000FF'
	font1 = FontProperties()
	font1.set_size('9')
	fontl = font1.copy()
	fontl.set_weight('bold')
	tb = Table(ax)#, bbox=[0.10,0.10,0.90,0.90])
	tb.auto_set_font_size(False)
	#tb.set_fontsize(100.0)
	width, height = 0.95/(ncols+1), 0.95/(nrows+1)
	for i in range(nrows):
		tb.add_cell(i,-1, width*2, height, text=rows[i][:20], loc='right',edgecolor=ecol, facecolor=rowlc,fontproperties=fontl)
	# Column Labels
	for j in range(ncols):
		tb.add_cell(-1, j, width, height/1.5, text=columns[j][:10], loc='center', edgecolor=ecol, facecolor=collc,fontproperties=fontl)
	tb.add_cell(-1,-1, width*2, height/1.5, text=rowname[:10], loc='right',edgecolor=ecol, facecolor=rowlc,fontproperties=fontl)

	# Add cells
	for i in range(len(data)):
		for j in range(len(data[i])):
			val = data[i][j]
			tb.add_cell(i,j,width, height, text=fmt.format(val), loc='center', edgecolor=ecol, facecolor=cellc, fontproperties=font1)
	# Row Labels
	ax.add_table(tb)
	plt.savefig(folder+'/'+title+'.pdf')
	#plt.show()
	#sys.exit(0)
	plt.close()
Exemple #12
0
def gcm_heatmaps(gcms, ginfo, out_file, title_tag, colormap='RdYlBu_r'):

    with PdfPages(out_file) as pdf:
        font0 = FontProperties()
        font0.set_name('sans-serif')
        font0.set_size(12)
        font1 = font0.copy()
        font1.set_size(14)
        font2 = font0.copy()
        font2.set_size(16)

        for i, GCM in enumerate(gcms):

            title = "%s (|cor|> %.3f, %d nodes, %d edges)" % \
                    (title_tag, ginfo.loc[i, 'AbsCor'],
                     ginfo.loc[i, 'NumNodes'],
                     ginfo.loc[i, 'NumEdges'])

            fig = plt.figure(1, figsize=(8, 8))
            ax = fig.add_subplot(111)
            im = ax.matshow(GCM,
                            aspect='equal',
                            cmap=matplotlib.cm.get_cmap(colormap),
                            vmin=-1.0,
                            vmax=1.0)
            ax.set_title(title, fontproperties=font2)

            labels = list(map(str, GCM_ORDER))
            xticks = np.arange(len(labels))
            yticks = np.arange(len(labels))
            ax.set_xticks(xticks)
            ax.set_yticks(yticks)
            ax.set_xticklabels(labels, fontproperties=font1)
            ax.set_yticklabels(labels, fontproperties=font1)

            plt.setp(list(ax.spines.values()), lw=0.5, color="#666666")
            plt.setp(ax.get_xticklabels(), fontproperties=font1)
            plt.setp(ax.get_yticklabels(), fontproperties=font1)
            plt.setp(ax.xaxis.get_ticklines(), markersize=3)
            plt.setp(ax.yaxis.get_ticklines(), markersize=3)
            plt.setp(ax.xaxis.get_ticklines(minor=True), markersize=1)
            plt.setp(ax.yaxis.get_ticklines(minor=True), markersize=1)
            ax.xaxis.set_ticks_position('bottom')
            ax.yaxis.set_ticks_position('right')

            pdf.savefig()
            plt.close()
Exemple #13
0
    def set_defaults(self):
        self.zoom_x = 0
        self.zoom_y = 0
        self.zoom_init = (0, 1)

        self.title  = ' '
        self.xlabel = ' '
        self.ylabel = ' '
        self.y2label = ' '
        self.plot_type = 'lineplot'
        self.cursor_mode = 'zoom'
        self.scatter_size = 6
        self.scatter_normalcolor = 'blue'
        self.scatter_normaledge  = 'blue'
        self.scatter_selectcolor = 'red'
        self.scatter_selectedge  = 'red'
        self.scatter_data = None
        self.scatter_coll = None
        self.scatter_mask = None

        self.legend_loc    =  'upper right'
        self.legend_onaxis =  'on plot'
        self.mpl_legend  = None
        self.show_grid   = True
        self.show_legend = False
        self.show_legend_frame = False
        # self.trace_color_callback = trace_color_callback
        f0 =  FontProperties()
        self.labelfont = f0.copy()
        self.titlefont = f0.copy()
        self.labelfont.set_size(9)
        self.titlefont.set_size(10)
        self.textcolor = '#000000'
        self.grid_color = '#E5E5E5'
        # preload some traces
        self.ntrace = 0
        self.lines  = [None]*30
        self.traces = []
        self._init_trace( 0, 'blue',      'solid')
        self._init_trace( 1, 'red',       'solid')
        self._init_trace( 2, 'black',     'solid')
        self._init_trace( 3, 'magenta',   'solid')
        self._init_trace( 4, 'green3',    'solid')
        self._init_trace( 5, 'maroon',    'solid')
        self._init_trace( 6, 'blue',     'dashed')
        self._init_trace( 7, 'red',      'dashed')
        self._init_trace( 8, 'black',    'dashed')
        self._init_trace( 9, 'magenta',  'dashed')
        self._init_trace(10, 'green3',   'dashed')
        self._init_trace(11, 'maroon',   'dashed')
        self._init_trace(12, 'blue',     'dotted')
        self._init_trace(13, 'red',      'dotted')
        self._init_trace(14, 'black',    'dotted')
        self._init_trace(15, 'magenta',  'dotted')
        self._init_trace(16, 'green3',   'dotted')
        self._init_trace(17, 'maroon',   'dotted')
        self._init_trace(18, 'blue',      'solid', marker='+')
        self._init_trace(19, 'red',       'solid', marker='+')
        self._init_trace(20, 'black',     'solid', marker='o')
Exemple #14
0
def plot_ref_genome(ref_placements,cycle,total_length,segSeqD,imputed_status,label_segs,onco_set=set()):
    font0 = FontProperties()
    rot_sp = global_rot/360.*total_length
    for ind,refObj in ref_placements.iteritems():
        seg_coord_tup = segSeqD[cycle[ind][0]]
        # print(refObj.to_string())
        start_angle, end_angle = start_end_angle(refObj.abs_end_pos,refObj.abs_start_pos,total_length)
        # print start_angle,end_angle
        
        #makes the reference genome wedges    
        patches.append(mpatches.Wedge((0,0), outer_bar, end_angle, start_angle, width=bar_width))
        chrom = segSeqD[cycle[ind][0]][0]
        f_color_v.append(chromosome_colors[chrom])
        e_color_v.append('grey')
        lw_v.append(0.2)
        
        #makes the ticks on the reference genome wedges
        if cycle[ind][1] == "+":
            # posns = zip(range(seg_coord_tup[1],seg_coord_tup[2]+1),np.arange(refObj.abs_end_pos,refObj.abs_start_pos,-1))
            posns = zip(range(seg_coord_tup[1],seg_coord_tup[2]+1),np.arange(refObj.abs_start_pos,refObj.abs_end_pos))
        else:
            # posns = zip(np.arange(seg_coord_tup[2],seg_coord_tup[1]-1,-1),np.arange(refObj.abs_end_pos,refObj.abs_start_pos,-1))
            posns = zip(np.arange(seg_coord_tup[2],seg_coord_tup[1]-1,-1),np.arange(refObj.abs_start_pos,refObj.abs_end_pos))

        tick_freq = max(30000,30000*int(np.floor(total_length/1000000)))
        if refObj.abs_end_pos-refObj.abs_start_pos < 30000:
            tick_freq = 10000
        for j in posns:
            if j[0] % tick_freq == 0:
                text_angle = j[1]/total_length*360
                x,y = pol2cart(outer_bar,(text_angle/360*2*np.pi))
                x_t,y_t = pol2cart(outer_bar + 0.2,(text_angle/360*2*np.pi))
                ax.plot([x,x_t],[y,y_t],color='grey',linewidth=1)
                
                text_angle,ha = vu.correct_text_angle(text_angle)
                txt = " " + str(int(round((j[0])/10000))) if ha == "left" else str(int(round((j[0])/10000))) + " "

                ax.text(x_t,y_t,txt,color='grey',rotation=text_angle,
                ha=ha,va="center",fontsize=9,rotation_mode='anchor')
    
        gene_tree = vu.parse_genes(seg_coord_tup[0],args.ref)
        relGenes = vu.rel_genes(gene_tree,seg_coord_tup,copy.copy(onco_set))
        #plot the gene track
        plot_gene_track(refObj.abs_start_pos,relGenes,seg_coord_tup,total_length,cycle[ind][1])

        #label the segments by number in cycle
        mid_sp = (refObj.abs_end_pos + refObj.abs_start_pos)/2
        text_angle = mid_sp/total_length*360.
        x,y = pol2cart((outer_bar-2*bar_width),(text_angle/360.*2.*np.pi))
        font = font0.copy()
        if imputed_status[ind]:
            font.set_style('italic')
            # font.set_weight('bold')

        text_angle,ha = vu.correct_text_angle(text_angle)

        if label_segs:
            ax.text(x,y,cycle[ind][0]+cycle[ind][1],color='grey',rotation=text_angle,
                ha=ha,fontsize=5,fontproperties=font,rotation_mode='anchor')
Exemple #15
0
    def __init__(self):
        self.axes   = None
        self.canvas = None
        self.fig    = None
        self.zoom_x = 0
        self.zoom_y = 0
        self.zoom_init = (0,1)
        
        self.title  = ' '
        self.xlabel = ' '
        self.ylabel = ' '
        self.styles      = StyleMap.keys()
        self.symbols     = MarkerMap.keys()
        self.legend_locs = ['upper right' , 'upper left', 'upper center',
                            'lower right',  'lower left', 'lower center',
                            'center left',  'center right', 'right', 'center']
        self.legend_onaxis_choices =  ['on plot', 'off plot']

        self.legend_loc    =  'upper right'
        self.legend_onaxis =  'on plot'
        self.mpl_legend  = None
        self.show_grid   = True
        self.show_legend = False
        self.show_legend_frame = True

        f0 =  FontProperties()
        self.labelfont = f0.copy()
        self.titlefont = f0.copy()
        self.labelfont.set_size(12)
        self.titlefont.set_size(14)

        self.grid_color = '#E0E0E0'
        # preload some traces
        #                   color  style linewidth marker markersize
        self.ntrace = 0
        self.lines  = [None]*30
        self.traces = []
        self._init_trace(20,None, 'black'    ,'dotted',2,'o', 8)
        self._init_trace( 0,None, 'blue',     'solid', 2,None,8)
        self._init_trace( 1,None, 'red',      'solid', 2,None,8)
        self._init_trace( 2,None, 'black',    'solid', 2,None,8)
        self._init_trace( 3,None, 'magenta',  'solid', 2,None,8)
        self._init_trace( 4,None, 'darkgreen','solid', 2,None,8)
        self._init_trace( 5,None, 'maroon'   ,'solid', 2,None,8)
        self._init_trace( 6,None, 'blue',     'dashed',2,None,8)
        self._init_trace( 7,None, 'red',      'dashed',2,None,8)
        self._init_trace( 8,None, 'black',    'dashed',2,None,8)
        self._init_trace( 9,None, 'magenta',  'dashed',2,None,8)
        self._init_trace(10,None, 'darkgreen','dashed',2,None,8)
        self._init_trace(11,None, 'maroon'   ,'dashed',2,None,8)
        self._init_trace(12,None, 'blue',     'dotted',2,None,8)
        self._init_trace(13,None, 'red',      'dotted',2,None,8)
        self._init_trace(14,None, 'black',    'dotted',2,None,8)
        self._init_trace(15,None, 'magenta',  'dotted',2,None,8)
        self._init_trace(16,None, 'darkgreen','dotted',2,None,8)
        self._init_trace(17,None, 'maroon'   ,'dotted',2,None,8)
        self._init_trace(18,None, 'blue'     ,'solid',1,'+',8)
        self._init_trace(19,None, 'red'      ,'solid',1,'+',8)
Exemple #16
0
    def get_font(self):
        font_properties = FontProperties()
        font = font_properties.copy()
        font.set_size(str(self.font_point.GetValue()))
        font.set_name(str(self.font_family.GetValue()))
        font.set_slant(str(self.font_style.GetValue()))
        font.set_weight(str(self.font_weight.GetValue()))

        return font
Exemple #17
0
    def __init__(self,aniso_depth_file,**input_parameters):
        self.levels = None
        self.n_levels = 10
        self.escale = 0.001
        self.anisotropy_threshold = [1.,100]
        self.cmap = 'jet_r'
        self.scaleby = 'resmin'
        self.anisotropy_display_factor = 0.75
        self.xlim = None
        self.ylim = None
        self.plot_cbar=True
        self.cbar_ax = [0.8,0.1,0.08,0.8]
        self.imethod = 'linear'
        self.scalebar = True
        self.aniso_depth_file = aniso_depth_file
        self.aniso_depth_file_dict = dict(header_rows=1,
                                          scale='km')
        self.xyzfiles = None
        self.xyzfiles_dict = dict(header_rows=1,
                                  scale='km')
        self.xyzfile_titles = None
        self.additional_xy_data = {}
        self.plot_text = {}
        self.set_titles = True

        self.subplot_layout = 'vertical'
        self.wspace = 0.02
        self.hspace = 0.15
        self.fonttype = 'serif'
        self.figsize=(8,5)
        
        for key in input_parameters.keys():
            if hasattr(self,str.lower(key)):
                setattr(self,key,input_parameters[key]) 
                
        
            
        self.read_aniso_depth_data()
        if self.xyzfiles is not None:
            if type(self.xyzfiles) == str:
                self.xyzfiles = [self.xyzfiles]
            if self.xyzfile_titles is None:
                titles = []
                for f in self.xyzfiles:
                    titles.append(op.basename(f))
                self.xyzfile_titles = titles
            else:
                if type(self.xyzfile_titles) == str:
                    self.xyzfile_titles = [self.xyzfile_titles]
                while len(self.xyzfile_titles) < len(self.xyzfiles):
                    self.xyzfile_titles.append('')

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font                   
def CalibrationRiseTime(calibration_filename):
    # Read data fron the calibration curve dataset
    C, e_C, noise_rms, d_noise_rms, fall_time, d_fall_time, amplitude, d_amplitude = LoadCalibrationFile(calibration_filename)

    gStyle.SetOptStat(1111)

    # Construct the  curve
    calib_curve = TGraphErrors(len(C), array('d',C.tolist()), array('d', fall_time.tolist()), array('d', e_C.tolist()), array('d',d_fall_time.tolist()) )

    # Construct the fit with a 2nd order polynomial
    fit_curve = TF1('fit_curve','[0]*x*x + [1]*x + [2]',0.,110.)
    fit_curve.SetParameter(0, 0.0)
    fit_curve.SetParameter(1, 0.0)
    fit_curve.SetParameter(2, 0.0)
    fit_curve.SetLineColor(2)

    # FIt the calibration curve
    calib_curve.Fit(fit_curve,'R')

    # Extract the results fron the fit
    par0   = fit_curve.GetParameter(0)
    e_par0 = fit_curve.GetParError(0)
    par1   = fit_curve.GetParameter(1)
    e_par1 = fit_curve.GetParError(1)
    par2   = fit_curve.GetParameter(2)
    e_par2 = fit_curve.GetParError(2)

    xx = np.linspace(0., 105, 1000)
    yy = [fit_curve.Eval(x) for x in xx]
    par = [par2, par1, par0]
    l = 'fit pol2 $p_0$: {:.3g} $p_1$: {:.3g} $p_2$: {:.2f}'.format(*par)

    # Plot the calibration curve with matplotlib
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('x-large')

    fig, ax = plt.subplots()
    ax.set_xlabel('C [pF]')
    ax.set_xlim(0.0, 120)
    ax.set_ylabel('Rise time [ns]')
    ax.errorbar(C, fall_time, d_fall_time, marker='o', color='k', linestyle='None', label='Data')
    ax.plot(xx, yy, label=l, color='r')
    #plt.set_title('Diode calibration curve')
    ax.text(0.05,0.65, 'Group 1', verticalalignment='bottom', horizontalalignment='left',
                fontproperties=font, transform=ax.transAxes)
    ax.legend(loc='upper left', numpoints=1)
    plt.grid()
    #plt.show()
    fig.savefig('../graphics/calibration_diode.pdf')
    plt.close(fig)
    plt.clf()

    return par0, e_par0, par1, e_par1, par2, e_par2
Exemple #19
0
def plot_histo( ydata , fileout , color ):
    ##  Define figure enviroment
    fig = plt.figure(1)
    rect = fig.patch
    rect.set_facecolor('white')
    axescolor  = '#f6f6f6'
    ax = plt.subplot(111,axisbg=axescolor)


    ##  Font setting
    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = font1.copy()
    font.set_family('serif')
    rc('text',usetex=True)
    

    ##  Enable grid
    gridLineWidth = 0.2
    ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.05')


    ##  Marker setup
    colors = [ 'blue' , 'red' , 'blue','red','green','black','brown','orange','black','violet']
    markers = ['^','s','o','d','1','v']


    ##  Ticks
    xdensity=100
    fig.autofmt_xdate(bottom=0.18)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    locs,xlabels = plt.xticks()
    #locs = np.arange(xinf,xsup,xdensity)
    #plt.xticks(locs, map(lambda x: "%d" % x, locs))
    locs,ylabels = plt.yticks() 
    #plt.yticks(locs, map(lambda x: "%e" % x, locs)) 

    
    ##  Set title and axis labeling
    plt.xlabel(r'\textbf{Grey value}', fontsize=18,position=(0.5,-0.2))
    plt.ylabel( r'\textbf{Counts}' , fontsize=18,position=(0.5,0.5))
    plt.suptitle(r'\textbf{HISTOGRAM}', fontsize=16, fontweight='bold',
                 position=(0.53,0.95))
                                                               
    
    ##  Plot histogram
    n, bins, patches = plt.hist( ydata , 256 , facecolor=color, edgecolor='none' , alpha=1.0 )

    
    ##  Save plot and show it
    #plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' )    
    plt.savefig( fileout , facecolor=fig.get_facecolor() , #edgecolor='black' ,
                 format='eps', dpi=1000)   
    plt.show() 
    def __init__(self, Model_suite, **input_parameters):

        self.Model_suite = Model_suite
        self.working_directory = Model_suite.working_directory
        self.parameters = [['minmax'], ['aniso', 'strike']]
        self.titles = {
            'minmax': 'Minimum and maximum resistivity, $\Omega m$',
            'aniso':
            'Anisotropy in resistivity',  # (maximum/minimum resistivity)
            'strike': 'Strike angle of minimum resistivity'
        }  #, $^\circ$
        self.xlim = {
            'minmax': [0.1, 1000],
            'aniso': [0, 20],
            'strike': [0, 180]
        }

        self.ylim = [6, 0]
        self.modelno = Model_suite.modelno
        self.modeltype = 'model'
        self.rotation_angle = 0.

        self.station_listfile = None
        self.station_xyfile = None

        self.figsize = (6, 6)
        self.plot_spacing = 0.1
        self.title_type = 'single'
        self.fonttype = 'sans-serif'
        self.label_fontsize = 8
        self.title_fontsize = 12
        self.linedict = dict(style='-', width=1, colour=[['0.5', 'k']] * 2)
        self.horizon_list = None
        self.horizon_zscale = 'km'
        self.horizon_linedict = dict(style=['-'] * 6,
                                     width=[2] * 6,
                                     colour=['c', 'y', 'b', 'r', 'g', 'm'])

        self.subplot_dict = dict(wspace=0.1, bottom=0.25, hspace=0.4)

        # store inputs in the object to pass through to Plot_model object
        self.input_parameters = input_parameters

        # set attributes from keyword arguments
        for key in input_parameters.keys():
            if hasattr(self, key):
                setattr(self, key, input_parameters[key])
                self.input_parameters[key] = input_parameters[key]

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font

        self.working_directory = os.path.abspath(self.working_directory)
Exemple #21
0
    def __init__(self, aniso_depth_file, **input_parameters):
        self.levels = None
        self.n_levels = 10
        self.escale = 0.001
        self.anisotropy_threshold = [1., 100]
        self.cmap = 'jet_r'
        self.scaleby = 'resmin'
        self.anisotropy_display_factor = 0.75
        self.xlim = None
        self.ylim = None
        self.plot_cbar = True
        self.cbar_ax = [0.8, 0.1, 0.08, 0.8]
        self.imethod = 'linear'
        self.scalebar = True
        self.aniso_depth_file = aniso_depth_file
        self.aniso_depth_file_dict = dict(header_rows=1,
                                          scale='km')
        self.xyzfiles = None
        self.xyzfiles_dict = dict(header_rows=1,
                                  scale='km')
        self.xyzfile_titles = None
        self.additional_xy_data = {}
        self.plot_text = {}
        self.set_titles = True

        self.subplot_layout = 'vertical'
        self.wspace = 0.02
        self.hspace = 0.15
        self.fonttype = 'serif'
        self.figsize = (8, 5)

        for key in input_parameters.keys():
            if hasattr(self, str.lower(key)):
                setattr(self, key, input_parameters[key])

        self.read_aniso_depth_data()
        if self.xyzfiles is not None:
            if isinstance(self.xyzfiles, str):
                self.xyzfiles = [self.xyzfiles]
            if self.xyzfile_titles is None:
                titles = []
                for f in self.xyzfiles:
                    titles.append(op.basename(f))
                self.xyzfile_titles = titles
            else:
                if isinstance(self.xyzfile_titles, str):
                    self.xyzfile_titles = [self.xyzfile_titles]
                while len(self.xyzfile_titles) < len(self.xyzfiles):
                    self.xyzfile_titles.append('')

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font
def whoswho(X, y, image_file):  
    # Train the whole entire data set !!
    md_pca, Xtrain_proj = pca_X(X, n_comp = 50)
    md_clf = svm_train(Xtrain_proj, y)
    
    # Load in test photo (whoswho.JPG) and crop them
    whoswho = image_file
    orig_im = image.imread(whoswho)
    images, faces = crop_images(orig_im)
    
    # goes through cropped images and called pca_svm_pred and for each prediction
    # it will print out the prediction made and add to the preds list.
    preds = []
    for i in range(len(images)):
        preds.append(pca_svm_pred(images[i], md_pca, md_clf))
        print("PCA+SVM predition for person", i, ":", names_dict.get(preds[i][0]))
      
    n_row = 1
    n_col = 3

    # this will plot each cropped image with a title of what the prediction was
    for i in range (n_row * n_col):
        plt.subplot(n_row, n_col, i+1)
        plt.imshow(images[i], cmap = plt.cm.gray)
        plt.title("Person" + str(i) + ": " + names_dict.get(preds[i][0]))
        plt.axis('off')
    

    # Create figure and show original image
    fig = plt.figure(figsize = (8, 8))
    ax = plt.subplot(111)
    ax.imshow(orig_im)
    plt.grid('off')
    plt.axis('off')
    
    # Set font
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('large')
    
    # This will put text (predictions) on the current plt image. 
    j = 0
    for (x, y, w, h) in faces:
        plt.text(x + 100, y, names_dict.get(preds[j][0]), color='pink', \
            size = 12, fontproperties = font)
        j+=1

    plt.show()
    
    return images
Exemple #23
0
    def __init__(self,Model_suite,**input_parameters):
        
        self.Model_suite = Model_suite
        self.working_directory = Model_suite.working_directory
        self.parameters = [['minmax'],['aniso','strike']]
        self.titles = {'minmax':'Minimum and maximum resistivity, $\Omega m$',
                       'aniso':'Anisotropy in resistivity',# (maximum/minimum resistivity)
                       'strike':'Strike angle of minimum resistivity'}#, $^\circ$
        self.xlim = {'minmax':[0.1,1000],
                     'aniso':[0,20],
                     'strike':[0,180]}

        self.ylim = [6,0]
        self.modelno = Model_suite.modelno
        self.modeltype = 'model'
        self.rotation_angle = 0.
        
        
        self.station_listfile = None
        self.station_xyfile = None
        
        self.figsize = (6,6)
        self.plot_spacing = 0.1
        self.title_type = 'single'
        self.fonttype = 'sans-serif'
        self.label_fontsize = 8
        self.title_fontsize = 12
        self.linedict = dict(style='-',width=1,
                              colour=[['0.5','k']]*2)
        self.horizon_list = None
        self.horizon_zscale = 'km'
        self.horizon_linedict = dict(style=['-']*6,width=[2]*6,
                                     colour=['c','y','b','r','g','m'])
                                     
                                     
        self.subplot_dict = dict(wspace=0.1,bottom=0.25,hspace=0.4)
        
        # store inputs in the object to pass through to Plot_model object
        self.input_parameters = input_parameters

        # set attributes from keyword arguments          
        for key in input_parameters.keys():
            if hasattr(self,key):
                setattr(self,key,input_parameters[key])
                self.input_parameters[key] = input_parameters[key]

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font
            
        self.working_directory = os.path.abspath(self.working_directory)
def boldAnnot(ax, x, y, txt, ha='left', va='top', size=12):
    font0 = FontProperties()
    boldFont = font0.copy()
    boldFont.set_weight('bold')
    boldFont.set_size(size)
    ax.text(x,
            y,
            txt,
            transform=ax.transAxes,
            ha=ha,
            va=va,
            fontsize=size,
            fontproperties=boldFont)
Exemple #25
0
def naslov(ttitle, x_label, y_label):
    ax = plt.subplot(111)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    plt.grid(linestyle=':', linewidth=0.95, color='seagreen')
    from matplotlib.font_manager import FontProperties
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_size('x-large')
    font.set_family('serif')
    plt.title(ttitle, fontsize='14')
    plt.xlabel(x_label, fontsize='14')
    plt.ylabel(y_label, fontsize='14')
    plt.legend()
Exemple #26
0
def plot_function( curves , n , args ):
    ##  Common plot settings
    if n == 1:
        y = curves.copy()
    if n == 2:
        y = curves[0]
        yfit = curves[1]
    npix = len( y )
    y = y.astype( myfloat )
    x = np.arange(npix).astype(myfloat) 
    fig = plt.figure(1)
    rect = fig.patch
    rect.set_facecolor('white')
    axescolor  = '#f6f6f6'
    ax = plt.subplot(111,axisbg=axescolor)  
    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = font1.copy()
    font.set_family('serif')
    rc('text',usetex=True)  
    gridLineWidth = 0.2
    ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.05')  
    fig.autofmt_xdate(bottom=0.18)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)  
    plt.xlabel(r'\textbf{Pixel index}', fontsize=18,position=(0.5,-0.2))
    plt.ylabel( r'\textbf{Grey value}' , fontsize=18,position=(0.5,0.5))

    if n == 1:
        plt.suptitle(r'\textbf{Input line profile}', fontsize=16, fontweight='bold',
                     position=(0.53,0.95))     
        plt.plot( x , y , linewidth=4 , color='b' ) 
    elif n == 2:
        plt.suptitle(r'\textbf{Line profile fitted with ERF}', fontsize=16, fontweight='bold',
                     position=(0.53,0.95)) 
        plt.plot( x , y , 'o' , markersize=6 , color='b' )
        plt.hold( True )
        plt.plot( x , yfit , linewidth=4 , color='r' )
    
    if n == 2 and args.saveplots is not None:
        fileout = args.saveplots
        #plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' )    
        plt.savefig( fileout , facecolor=fig.get_facecolor() , #edgecolor='black' ,
                     format='eps', dpi=1000) 

    if args.plot is True:
        plt.show() 
Exemple #27
0
def cal(cfg, science, bias_image, darks, flats):
    al_science = deepcopy(science)
    filts = _gather_filters(science)
    for filt in filts:
        if filt in flats:
            files = [x for x in al_science if filt in x]
            files.sort()
            for i, f in enumerate(files):
                header, data = list(map(lambda x: x[0], nkrpy_read(f)))
                exptime = header['EXPTIME'] if header['EXPTIME'] \
                    else header['EXPOSURE']
                if darks is not None:
                    dark_image = scale_dark(files=darks, fin_exposure=exptime)
                if bias_image is not None:
                    data -= bias_image
                if dark_image is not None:
                    data -= dark_image
                data /= flats[filt]

                dest = os.path.join(os.getcwd(), cfg.destination)
                _t = "_".join(f.split("_")[0:2]).split("/")[-1]
                _temp = f'{dest}/{_t}_{i}.fits'
                if cfg.createfits:
                    while not nkrpy_write(f'{_temp}', header=header,
                                          data=data):
                        continue

                if cfg.createplot:
                    os.chdir(os.path.join(cfg._cwd, cfg.destination))

                    fig = plt.figure(figsize=(10, 10))
                    font0 = FontProperties()
                    font = font0.copy()
                    font.set_weight('bold')
                    ax = fig.add_subplot(1, 1, 1)
                    ax.tick_params(axis='x', labelsize=25)
                    ax.tick_params(axis='y', labelsize=25)
                    ax.get_xaxis().set_ticks([])
                    ax.get_yaxis().set_ticks([])
                    plot_image(data,
                               _temp.split('/')[-1],
                               fig,
                               ax,
                               color=False)
                os.chdir(cfg._cwd)
    pass
def plot_function( curves , n , args ):
    ##  Common plot settings
    if n == 1:
        y = curves.copy()
    if n == 2:
        y = curves[0]
        yfit = curves[1]
    npix = len( y )
    y = y.astype( myfloat )
    x = np.arange(npix).astype(myfloat) 
    fig = plt.figure(1)
    rect = fig.patch
    rect.set_facecolor('white')
    axescolor  = '#f6f6f6'
    ax = plt.subplot(111,axisbg=axescolor)  
    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = font1.copy()
    font.set_family('serif')
    rc('text',usetex=True)  
    gridLineWidth = 0.2
    ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.05')  
    fig.autofmt_xdate(bottom=0.18)
    plt.xticks(fontsize=12)
    plt.yticks(fontsize=12)  
    plt.xlabel('Pixel index', fontsize=12,position=(0.5,-0.2))
    plt.ylabel( 'Grey value' , fontsize=12,position=(0.5,0.5))

    if n == 1:
        plt.title('Input line profile', fontsize=12, fontweight='bold')
        plt.plot( x , y , linewidth=2 , color='b' ) 
    elif n == 2:
        plt.title('Line profile fitted with ERF', fontsize=12, fontweight='bold')
        plt.plot( x , y , linewidth=2 , color='blue' , label='Line profile' )
        plt.hold( True )
        plt.plot( x , yfit , linewidth=3 , color='r' , label='Erf fit function' )
        plt.legend(loc='upper right', shadow=True)
    
    if n == 2 and args.saveplots is not None:
        fileout = args.saveplots
        plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' ,
                     format='eps', dpi=1000) 

    if args.plot is True:
        plt.show() 
Exemple #29
0
def computeMDS(inputFile):
    new_reader = pd.read_excel(inputFile, index_col=0)

    size = new_reader.shape
    for j in range(size[1]):
        for i in range(size[0]):
            new_reader.iloc[i,j]=new_reader.iloc[j,i]
            if (i==j):
                new_reader.iloc[i,j]= 0.00


    adist = np.array(new_reader)
    amax = np.amax(adist)
    adist /= amax

    cities1 = [r.encode('utf-8') for r in list(new_reader.index)]

    mds = manifold.MDS(n_components=2, dissimilarity="precomputed", random_state=6)
    results = mds.fit(adist)

    coords = results.embedding_
    plt.subplots_adjust(bottom = 0.1)
    plt.scatter(
        coords[:, 0], coords[:, 1], marker = 'o'
        )
    font0 = FontProperties()
    font = font0.copy()

    ## Change the size of the font
    ## Sizes: ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
    font.set_size('xx-large')


    for label, x, y in zip(cities1, coords[:, 0], coords[:, 1]):
        plt.annotate(
            label,
            xy = (x, y), xytext = (-20, 20),
             fontproperties=font,
            textcoords = 'offset points', ha = 'right', va = 'bottom',
            bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
            arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))


    plt.savefig('MDS.png')
    print ('MDS plot can be found at MDS.png')
Exemple #30
0
    def __init__(self, axes=None, fig=None, canvas=None):
        self.axes   = axes
        self.fig  = fig
        self.canvas  = canvas
        self.cmap  = colormap.gray
        self.cmap_reverse = False
        self.interp = 'nearest'
        self.title   = 'map'
        self.log_scale = False
        self.cmap_lo = 0
        self.cmap_hi = self.cmap_range = 100
        # self.zoombrush = wx.Brush('#141430',  wx.SOLID)
        self.zoombrush = wx.Brush('#040410',  wx.SOLID)
        self.zoompen   = wx.Pen('#101090',  3, wx.SOLID)

        f0 =  FontProperties()
        self.titlefont = f0.copy()
        self.titlefont.set_size(14)
Exemple #31
0
    def add_text(self):
        """
        Text in the plot
        """
        if not self.is_number:
            return

        self.clear()
        try:
            self.figure.delaxes(self.figure.axes[0])
            self.subplot = self.figure.add_subplot(111)
            self.figure.delaxes(self.figure.axes[1])
        except:
            pass
        self.subplot.set_xticks([])
        self.subplot.set_yticks([])
        label = self.content
        FONT = FontProperties()
        xpos, ypos = (0.4, 0.5)
        font = FONT.copy()
        font.set_size(14)

        self.textList = []
        self.subplot.set_xlim((0, 1))
        self.subplot.set_ylim((0, 1))

        try:
            if self.content != '?':
                float(label)
        except:
            self.subplot.set_frame_on(False)
        try:
            # mpl >= 1.1.0
            self.figure.tight_layout()
        except:
            self.figure.subplots_adjust(left=0.1, bottom=0.1)
        if len(label) > 0 and xpos > 0 and ypos > 0:
            new_text = self.subplot.text(str(xpos),
                                         str(ypos),
                                         str(label),
                                         fontproperties=font)
            self.textList.append(new_text)
Exemple #32
0
    def plot_location_map(self):
        """
        plot location map of all stations with profile shown on map.

        """

        if self.Model_suite.station_xyfile is None:
            print "can't get locations, no x y file"
            return

        if not hasattr(self, 'profile_origin'):
            self.get_profile_origin()

        font0 = FontProperties()
        font = font0.copy()
        font.set_family('serif')

        xy_all = np.genfromtxt(
            self.Model_suite.station_xyfile,
            invalid_raise=False)[
            :,
            1:]
        plt.plot(xy_all[:, 0], xy_all[:, 1], '.', c='0.5')

        m, c = self.profile
        x0, y0 = self.profile_origin

        if m > 1:
            y1 = max(self.Model_suite.y)
            x1 = (y1 - c) / m
        else:
            x1 = max(self.Model_suite.x)
            y1 = m * x1 + c

        plt.plot([x0, x1], [y0, y1], 'k')
        plt.plot(self.Model_suite.x, self.Model_suite.y, 'k.')

        ax = plt.gca()
        for label in ax.get_yticklabels():
            label.set_fontproperties(font)
        for label in ax.get_xticklabels():
            label.set_fontproperties(font)
    def add_text(self):
        """
        Text in the plot
        """
        if not self.is_number:
            return

        self.clear()
        try:
            self.figure.delaxes(self.figure.axes[0])
            self.subplot = self.figure.add_subplot(111)
            self.figure.delaxes(self.figure.axes[1])
        except:
            pass
        self.subplot.set_xticks([])
        self.subplot.set_yticks([])
        label = self.content
        FONT = FontProperties()
        xpos, ypos = (0.4, 0.5)
        font = FONT.copy()
        font.set_size(14)

        self.textList = []
        self.subplot.set_xlim((0, 1))
        self.subplot.set_ylim((0, 1))

        try:
            if self.content != '?':
                float(label)
        except:
            self.subplot.set_frame_on(False)
        try:
            # mpl >= 1.1.0
            self.figure.tight_layout()
        except:
            self.figure.subplots_adjust(left=0.1, bottom=0.1)
        if len(label) > 0 and xpos > 0 and ypos > 0:
            new_text = self.subplot.text(str(xpos), str(ypos), str(label),
                                           fontproperties=font)
            self.textList.append(new_text)
Exemple #34
0
 def onEditLabels(self, event):
     """
     Edit legend label
     """
     try:
         selected_plot = self.plots[self.graph.selected_plottable]
     except:
         selected_plot = self.plots[self.data2D.id]
     label = selected_plot.label
     dial = TextDialog(None, -1, 'Change Label', label)
     if dial.ShowModal() == wx.ID_OK:
         try:
             FONT = FontProperties()
             newlabel = dial.getText()
             font = FONT.copy()
             font.set_size(dial.getSize())
             font.set_family(dial.getFamily())
             font.set_style(dial.getStyle())
             font.set_weight(dial.getWeight())
             colour = dial.getColor()
             if len(newlabel) > 0:
                 # update Label
                 selected_plot.label = newlabel
                 self.graph.title(newlabel)
                 self.title_label = selected_plot.label
                 self.title_font = font
                 self.title_color = colour
                 ## render the graph
                 self.subplot.set_title(label=self.title_label,
                                        fontproperties=self.title_font,
                                        color=self.title_color)
                 self._is_changed_legend_label = True
                 self.subplot.figure.canvas.draw_idle()
         except:
             msg = "Add Text: Error. Check your property values..."
             logger.error(msg)
             if self.parent is not None:
                 wx.PostEvent(self.parent, StatusEvent(status=msg))
     dial.Destroy()
Exemple #35
0
    def __init__(self, Model_suite, **input_parameters):

        self.working_directory = '.'
        self.station_listfile = None
        self.station_xyfile = None
        self.Model_suite = Model_suite
        self.modeltype = 'model'
        self.fig_width = 1.
        self.ax_width = 0.03
        self.ax_height = 0.8
        self.ax_bottom = 0.1
        self.plot_spacing = 0.02
        self.ylim = [6, 0]
        self.title_type = 'single'
        self.titles = {
            'minmax': 'Minimum and maximum resistivity, $\Omega m$',
            'aniso':
            'Anisotropy in resistivity',  # (maximum/minimum resistivity)
            'strike': 'Strike angle of minimum resistivity'
        }  #, $^\circ$
        self.xlim = {
            'minmax': [0.1, 1000],
            'aniso': [0, 20],
            'strike': [0, 180]
        }
        self.fonttype = 'serif'
        self.label_fontsize = 8
        self.title_fontsize = 12

        for key in input_parameters.keys():
            setattr(self, key, input_parameters[key])

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font

        self.working_directory = os.path.abspath(self.working_directory)
Exemple #36
0
    def plot_location_map(self):
        """
        plot location map of all stations with profile shown on map.        
        
        """
        
        if self.Model_suite.station_xyfile is None:
            print "can't get locations, no x y file"
            return
        
        if not hasattr(self,'profile_origin'):
            self.get_profile_origin()

        font0 = FontProperties()
        font = font0.copy()
        font.set_family('serif')        
            
        xy_all = np.genfromtxt(self.Model_suite.station_xyfile,invalid_raise=False)[:,1:]
        plt.plot(xy_all[:,0],xy_all[:,1],'.',c='0.5')
        
        m,c = self.profile
        x0,y0 = self.profile_origin
        
        if m > 1:
            y1 = max(self.Model_suite.y)
            x1 = (y1-c)/m
        else:
            x1 = max(self.Model_suite.x)
            y1 = m*x1 + c
        
        plt.plot([x0,x1],[y0,y1],'k')
        plt.plot(self.Model_suite.x,self.Model_suite.y,'k.')
        
        ax=plt.gca()
        for label in ax.get_yticklabels():
            label.set_fontproperties(font)
        for label in ax.get_xticklabels():
            label.set_fontproperties(font)        
def set_font_label(ax, ylabel, xlabel, title):    
    font0 = FontProperties()
    font = font0.copy()
    font.set_family('arial')
    font.set_size(8)
    for label in ax.get_xticklabels():
        label.set_fontproperties(font)
    for label in ax.get_yticklabels():
        label.set_fontproperties(font)
    
    font.set_size(9)
    ax.set_ylabel(ylabel, fontproperties=font)
    ax.set_xlabel(xlabel, fontproperties=font, labelpad = 2)

    font.set_size(title[1])
    t = ax.set_title("\n".join(wrap(title[0], width = 26)), fontproperties=font)
    t.set_y(1.05)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params('both', direction = 'in', length=5, width=1, which='major')
    ax.locator_params(axis = 'X', nbins = 2)
def plot_info( xdata , ydata , fileout ):
    ##  Define figure enviroment
    fig = plt.figure(1)
    rect = fig.patch
    rect.set_facecolor('white')
    axescolor  = '#f6f6f6'
    ax = plt.subplot(111,axisbg=axescolor)


    ##  Font setting
    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = font1.copy()
    font.set_family('serif')
    rc('text',usetex=True)
    

    ##  Enable grid
    gridLineWidth = 0.2
    ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.05')


    ##  Marker setup
    colors = [ 'red' , 'blue' , 'green','blue','black','brown','orange','black','violet']
    markers = ['^','s','o','d','1','v']


    ##  Get xrange and yrange
    minx = np.min(xdata)
    maxx = np.max(xdata)
    miny = np.min(ydata)
    maxy = np.max(ydata)

    xinf = minx
    xsup = maxx
    yinf = miny
    ysup = maxy 

    plt.xlim([xinf-0.5,xsup+0.5])
    plt.ylim([yinf-0.1,ysup+0.1]) 

    
    ##  Ticks
    xdensity=40
    fig.autofmt_xdate(bottom=0.18)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    locs,xlabels = plt.xticks()
    locs = np.arange(xinf,xsup,xdensity)
    plt.xticks(locs, map(lambda x: "%d" % x, locs))

    
    ##  Set title and axis labeling
    plt.xlabel(r'\textbf{Pixel position}', fontsize=20,position=(0.5,-0.2))
    plt.ylabel( r'\textbf{Pixel value}' , fontsize=20,position=(0.5,0.5))          
                                                               
    
    ##  Plot each group data in the same final plot
    style = 'lines'
    labels = [ 'SPS' , 'ADMP-E' , 'ADMP-V' , 'ADMP-D' ]

    for i in range( ydata.shape[0] ):
        x = xdata
        y = ydata[i,:]
        
        if style == 'points':
            plt.plot( x , y , markers[i] , markersize=9, color=colors[i] ,
                    label=labels[i] )
        
        elif style == 'lines':
            if i < 0:
                plt.plot( x , y , color=colors[i] , linestyle='--' ,
                         linewidth=4.0 ,
                         label=labels[i] ) 
            else:
                plt.plot( x , y , color=colors[i] , linestyle='-' ,
                         linewidth=4.0 ,
                         label=labels[i] )
        plt.hold( True )

    plt.plot( x , yaux , color='blue' , linestyle='-' ,
              linewidth=4.0 , label='PHANTOM' )   

    
    ##  Add legend
    plt.legend( loc='upper center', bbox_to_anchor=(0.5, 1.1),
                ncol=4, fancybox=True, shadow=True )

    
    ##  Save plot and show it
    #plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' )    
    plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' ,
                 format='eps', dpi=1000)
    plt.show() 
Exemple #39
0
    def __init__(self, chan, host, fold=19277, nmax=100,NORM=True,sequence=False):
        self.UPDATE = True
        self.color  = True
        self.CMAP   = ['jet','seismic','Greys','plasma']
        self.COLORS = ['b','g','r']
        
        self.channel   = chan
        self.t         = time.time()
        self.NORM      = NORM
        self.shear     = 0.
        self.sequence  = sequence
        self.vmin      = -125
        self.vmax      = 125
        self.HORIZ_VAL = 0.05
        self.fold      = fold
        self.NMAX      = nmax
        
        ### To set the first name that has to be recorded ###
        try:
            L = C.getoutput('ls Image_*_DSA'+self.channel[0]+' | sort -n').splitlines()
            temp = array([eval(L[i].split('_')[1]) for i in range(len(L))])
            self.flag_save = max(temp) + 1
        except:                      # nothing in the folder already
            self.flag_save = 1
        
        for i in range(len(self.channel)):
            exec("self.remove_len1%d = 0" %i)
            exec("self.remove_len2%d = 1" %i)
        
        ### Establish the communication with the scope ###
        try:
            self.sock = vxi.Instrument(host)
            self.sock.write(':WAVeform:TYPE RAW')
            self.sock.write(':WAVEFORM:BYTEORDER LSBFirst')
            self.sock.write(':TIMEBASE:MODE MAIN')
            self.sock.write(':WAVEFORM:SOURCE ' + self.channel[0])
            self.sock.write(':WAVEFORM:FORMAT BYTE')
        except:
            print "\nWrong IP, Listening port or bad connection =>  Check cables first\n"
            sys.exit()
        
        ### Verify all channell provided are active ###
        for i in range(len(self.channel)):
            if self.query(':'+self.channel[i]+':DISP?')!='1\n':
                print "\nChannel "+self.channel[i]+' is not active...\n'
                sys.exit()
        
        ##################################################################
        ################## Start creating the figure #####################
        self.fig = figure(figsize=(16,7))
        
        ### trigger the scope for the first time ###
        self.single()
        self.load_data()
        if not(self.NMAX):
            self.NMAX = int(len(self.data0)/self.fold)
        self.update_tabs()
        self.Y0 = 0
        
        if len(self.channel)==1:
            self.declare_axis_1channel()
        elif len(self.channel)==2:
            self.declare_axis_2channel()
        elif len(self.channel)==3:
            self.declare_axis_3channel()
            
        for i in range(len(self.channel)):
            if not self.NORM:
                exec("self.im%d = self.ax%d.imshow(self.folded_data%d, interpolation='nearest', aspect='auto',origin='lower', vmin=self.vmin, vmax=self.vmax)" %(i,i,i))
            else:
                exec("self.im%d = self.ax%d.imshow(self.folded_data%d, interpolation='nearest', aspect='auto',origin='lower', vmin=self.folded_data%d.min(), vmax=self.folded_data%d.max())" %(i,i,i,i,i))

        for i in range(len(self.channel)):
            exec("self.cursor%d = Cursor(self.ax%d, useblit=True, color='red', linewidth=2)" %(i,i))
        
        self.axhh = axes([0.02,0.25,0.12,0.62])
        for i in range(len(self.channel)):
            exec("self.hline%d, = self.axh%d.plot(self.folded_data%d[self.Y0,:])" %(i,i,i))
            exec("self.axh%d.set_xlim(0,len(self.folded_data%d[0,:]))" %(i,i))
            exec("self.hhline%d, = self.axhh.plot(self.folded_data%d.mean(1),arange(self.NMAX),self.COLORS[i])" %(i,i))
        self.axhh.set_ylim(0,self.NMAX-1)
        if not self.NORM:
            for i in range(len(self.channel)):
                exec("self.axh%d.set_ylim(self.vmin, self.vmax)" %i)
            self.axhh.set_xlim(self.vmin, self.vmax)
        else:
            for i in range(len(self.channel)):
                 exec("self.axh%d.set_ylim(self.folded_data%d.min(), self.folded_data%d.max())" %(i,i,i))
            if len(self.channel)==1:
                LIM_MIN = self.folded_data0.mean(1).min()
                LIM_MAX = self.folded_data0.mean(1).max()
            elif len(self.channel)==2:
                LIM_MIN = min(self.folded_data0.mean(1).min(),self.folded_data1.mean(1).min())
                LIM_MAX = max(self.folded_data0.mean(1).max(),self.folded_data1.mean(1).max())
            elif len(self.channel)==3:
                LIM_MIN = min(self.folded_data0.mean(1).min(),self.folded_data1.mean(1).min(),self.folded_data2.mean(1).min())
                LIM_MAX = max(self.folded_data0.mean(1).max(),self.folded_data1.mean(1).max(),self.folded_data2.mean(1).max())
            self.axhh.set_xlim(LIM_MIN-1,LIM_MAX+1)
        
        # create 'remove_len1' slider
        for i in range(len(self.channel)):
            exec("self.remove_len1%d_slider   = Slider(self.remove_len1%d_sliderax,'beg',0.,self.fold,self.remove_len1%d,'%s')" %(i,i,i,'%d'))
            exec("self.remove_len1%d_slider.on_changed(self.update_tab)" %i)
        
        # create 'remove_len2' slider
        for i in range(len(self.channel)):
            exec("self.remove_len2%d_slider   = Slider(self.remove_len2%d_sliderax,'end',1.,self.fold,self.remove_len2%d,'%s')" %(i,i,i,'%d'))
            exec("self.remove_len2%d_slider.on_changed(self.update_tab)" %i)
        
        # create 'shear' slider
        self.shear_sliderax = axes([0.175,0.96,0.775,0.02])
        self.shear_slider   = Slider(self.shear_sliderax,'Shear',-0.5,0.5,self.shear,'%1.2f')
        self.shear_slider.on_changed(self.update_shear)
        
        #if self.sequence:
        VERT_VAL = -6
        font0 = FontProperties()
        font1 = font0.copy()
        font1.set_weight('bold')
        
        mpl.pyplot.text(-0.71,7+VERT_VAL,'Sequence mode:',fontsize=18,fontproperties=font1)
        mpl.pyplot.text(-0.71,3+VERT_VAL,'"b" to toggle it then:\n      "y" to save\n      "n" to next',fontsize=18)
        mpl.pyplot.text(-0.71,-32+VERT_VAL,'Useful keys:',fontsize=18,fontproperties=font1)
        mpl.pyplot.text(-0.71,-40+VERT_VAL,'"c" to change colormap\n "v" to change vertical\n      /colorscale\n " " to pause\n "S" to save trace\n       and picture\n "q" to exit',fontsize=18)
        #mpl.pyplot.text(-0.5,-27+VERT_VAL,'Sequence mode:',fontsize=18,fontproperties=font1)
        #mpl.pyplot.text(-0.37,-29.5+VERT_VAL,'"b" to toggle it then:\n      "y" to save\n      "n" to next',fontsize=18)
        #mpl.pyplot.text(0.15,-27+VERT_VAL,'Useful keys:',fontsize=18,fontproperties=font1)
        #mpl.pyplot.text(0.25,-31.5+VERT_VAL,'"c" to change colormap\n "v" to change vertical/colorscale\n " " to pause\n "S" to save trace and picture\n "q" to exit',fontsize=18)
        
        cid  = self.fig.canvas.mpl_connect('motion_notify_event', self.mousemove)
        cid2 = self.fig.canvas.mpl_connect('key_press_event', self.keypress)

        self.axe_toggledisplay  = self.fig.add_axes([0.,0.,1.0,0.02])
        self.plot_circle(0,0,2,fc='#00FF7F')
        mpl.pyplot.axis('off')
        
        gobject.idle_add(self.update_plot)
        show()
Exemple #40
0
import matplotlib.colors as mcolors
import matplotlib as mpl
from matplotlib.font_manager import FontProperties

font = {'family' : 'normal',
        'weight' : 'bold'}
#matplotlib.rc('font',**{'family':'Times', 'sans-serif':['Times']})
#matplotlib.rc('text', usetex = True)
#matplotlib.rc('font', **font)


plt.rcParams["font.family"] = "arial"   

font0 = FontProperties()
font = font0.copy()
weight = "bold"
font.set_weight(weight)  
      

#Color_list = [(0.306, 0.431+0.1, 0.545+0.3), (0.839+0.025, 0.60+0.05, 0.20), (0.839+0.16, 0.363, 0.35)]
Color_list = [(0.651, 0.325, 0.529), (0.839+0.025, 0.60+0.05, 0.20), (0.839+0.16, 0.363, 0.35)]

# Determine slope and intercept from Fitting-coral-cover.r 

# Data for GBR from source1: De'ath et al. 2012
source1Col = "#006024"#(0.173, 0.375, 0.187) 
GBR_Year_source1 = array([1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
                            1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012])
GBR_Cover_source1 = array([27.6392, 22.7458, 26.3999, 20.5105, 19.6836, 21.1800, 23.0085, 23.4262, 22.1840, 23.1825, 25.7579, 23.1051, 
                            20.8673, 25.4344, 24.2754, 23.0333, 20.6293,17.9764,17.4814, 21.7995, 16.3249,20.4771,15.5005, 18.5738, 
Exemple #41
0
def transitVisibilityPlot(allData, markTransit=False, plotLegend=True, showMoonDist=True, print2file=False):
  """
    Plot the visibility of transits.
    
    This function can conveniently be used with the output of
    the transitTimes function.
    
    Parameters
    ----------
    allData : dictionary
        Essentially the output of `transitTimes`.
        A dictionary mapping consecutive numbers (one per transit) to
        another dictionary providing the following keys:
        
          ============    ====================================================
          Key             Description
          ------------    ----------------------------------------------------
          Planet name     Name of the planet
          Transit jd      (Only if `markTransit is True)
                          Array giving JD of start, mid-time, and end of
                          transit.
          Obs jd          Array specifying the HJD of the start, center and
                          end of the observation.
          Obs cal         Equivalent to 'Obs jd', but in the form of the
                          calendar date. In particular, for each date, a list
                          containing [Year, month, day, fractional hours]
                          is given.
          Obs coord       East longitude [deg], latitude [deg], and
                          altitude [m] of the observatory.
          Star ra         Right ascension of the star [deg].
          Star dec        Declination of the star [deg].
          ============    ====================================================

        .. note:: To use the list created by transitTimes, the LONGITUDE and LATITUDE
                  of the observatory location must have been specified.
    markTransit : boolean, optional
        If True (default is False), the in-transit times will
        be clearly indicated in the plot.
        Note that this would not be the case otherwise, which is particularly
        important if extra off-transit time before and after the transit has been
        requested. 
    showMoonDist : boolean, optional
        If True (default), the Moon distance will be shown.
    print2file : boolean, optional
        If True, the plot will be dumped to a png-file named:
        "transitVis-"[planetName].png. The default is False.
  """
  from PyAstronomy.pyasl import _ic
  if not _ic.check["matplotlib"]:
    raise(PE.PyARequiredImport("matplotlib is not installed.", \
          where="transitVisibilityPlot", \
          solution="Install matplotlib (http://matplotlib.org/)"))
  
  import matplotlib
  import matplotlib.pylab as plt
  from mpl_toolkits.axes_grid1 import host_subplot
  from matplotlib.ticker import MultipleLocator
  from matplotlib.font_manager import FontProperties
  from matplotlib import rcParams
  
  rcParams['xtick.major.pad'] = 12 
  
  if len(allData.keys()) == 0:
    raise(PE.PyAValError("Input dictionary is empty", \
          where="transitVisibilityPlot", \
          solution=["Use `transitTimes` to generate input dictionary",
                    "Did you forget to supply observer's location?", \
                    "If you used `transitTime`, you might need to change the call argument (e.g., times)"]))
  
  # Check whether all relevant data have been specified
  reqK = ["Obs jd", "Obs coord", "Star ra", "Star dec", "Obs cal", "Planet name"]
  if markTransit:
    reqK.append("Transit jd")
  missingK = []
  for k in reqK:
    if not k in allData[1].keys():
      missingK.append(k)
  if len(missingK) > 0:
    raise(PE.PyAValError("The following keys are missing in the input dictionary: " + ', '.join(missingK), \
                         where="transitVisibilityPlot", \
                         solution="Did you specify observer's location in `transitTimes`?"))
  
  fig = plt.figure(figsize=(15,10))
  fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88)
  ax = host_subplot(111)

  font0 = FontProperties()
  font1 = font0.copy()
  font0.set_family('sans-serif')
  font0.set_weight('light')
  font1.set_family('sans-serif')
  font1.set_weight('medium')

  for n in allData.keys():
    # JD array
    jdbinsize = 1.0/24./10.
    jds = np.arange(allData[n]["Obs jd"][0], allData[n]["Obs jd"][2], jdbinsize)
    # Get JD floating point
    jdsub = jds - np.floor(jds[0])
    # Get alt/az of object
    altaz = eq2hor.eq2hor(jds, np.ones(jds.size)*allData[n]["Star ra"], np.ones(jds.size)*allData[n]["Star dec"], \
                        lon=allData[n]["Obs coord"][0], lat=allData[n]["Obs coord"][1], \
                        alt=allData[n]["Obs coord"][2])
    # Get alt/az of Sun
    sunpos_altaz = eq2hor.eq2hor(jds, np.ones(jds.size)*allData[n]["Sun ra"], np.ones(jds.size)*allData[n]["Sun dec"], \
                                lon=allData[n]["Obs coord"][0], lat=allData[n]["Obs coord"][1], \
                                alt=allData[n]["Obs coord"][2])
    
    # Define plot label
    plabel = "[%02d]  %02d.%02d.%4d" % (n, allData[n]["Obs cal"][0][2], \
                                        allData[n]["Obs cal"][0][1], allData[n]["Obs cal"][0][0])
    
    # Find periods of: day, twilight, and night
    day = np.where( sunpos_altaz[0] >= 0. )[0]
    twi = np.where( np.logical_and(sunpos_altaz[0] > -18., sunpos_altaz[0] < 0.) )[0]
    night = np.where( sunpos_altaz[0] <= -18. )[0]
    
    if (len(day) == 0) and (len(twi) == 0) and (len(night) == 0):
      print
      print "transitVisibilityPlot - no points to draw for date %2d.%2d.%4d" \
            % (allData[n]["Obs cal"][0][2], allData[n]["Obs cal"][0][1], allData[n]["Obs cal"][0][0])
      print "Skip transit and continue with next"
      print
      continue

    mpos = moonpos(jds)
    mpha = moonphase(jds)
    mpos_altaz = eq2hor.eq2hor(jds, mpos[0], mpos[1], lon=allData[n]["Obs coord"][0], \
                               lat=allData[n]["Obs coord"][1], alt=allData[n]["Obs coord"][2])
    moonind = np.where( mpos_altaz[0] > 0. )[0]

    if showMoonDist:
      mdist = getAngDist(mpos[0], mpos[1], np.ones(jds.size)*allData[n]["Star ra"], \
                         np.ones(jds.size)*allData[n]["Star dec"])
      bindist = int((2.0/24.)/jdbinsize)
      firstbin = np.random.randint(0,bindist)
      for mp in range(0, int(len(jds)/bindist)):
        bind = firstbin+float(mp)*bindist
        ax.text(jdsub[bind], altaz[0][bind]-1., str(int(mdist[bind]))+r"$^\circ$", ha="center", va="top", \
                fontsize=8, stretch='ultra-condensed', fontproperties=font0, alpha=1.)

    if markTransit:
      # Mark points within transit. These may differ from that pertaining to the
      # observation if an extra offset was given to provide off-transit time.
      transit_only_ind = np.where( np.logical_and(jds >= allData[n]["Transit jd"][0], \
                                                  jds <= allData[n]["Transit jd"][2]) )[0]
      ax.plot( jdsub[transit_only_ind], altaz[0][transit_only_ind], 'g', linewidth=6, alpha=.3)

    if len(twi) > 1:
      # There are points in twilight
      linebreak = np.where( (jdsub[twi][1:]-jdsub[twi][:-1]) > 2.0*jdbinsize)[0]
      if len(linebreak) > 0:
        plotrjd = np.insert(jdsub[twi], linebreak+1, np.nan)
        plotdat = np.insert(altaz[0][twi], linebreak+1, np.nan)
        ax.plot( plotrjd, plotdat, "-", color='#BEBEBE', linewidth=1.5)
      else:
        ax.plot( jdsub[twi], altaz[0][twi], "-", color='#BEBEBE', linewidth=1.5)

    ax.plot( jdsub[night], altaz[0][night], 'k', linewidth=1.5, label=plabel)
    ax.plot( jdsub[day], altaz[0][day], color='#FDB813', linewidth=1.5)
    
    altmax = np.argmax(altaz[0])
    ax.text( jdsub[altmax], altaz[0][altmax], str(n), color="b", fontsize=14, \
             fontproperties=font1, va="bottom", ha="center")

    if n == 29:
      ax.text( 1.1, 1.0-float(n)*0.04, "too many transits", ha="left", va="top", transform=ax.transAxes, \
              fontsize=10, fontproperties=font0, color="r")      
    else:
      ax.text( 1.1, 1.0-float(n)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \
              fontsize=12, fontproperties=font0, color="b")

  ax.text( 1.1, 1.03, "Start of observation", ha="left", va="top", transform=ax.transAxes, \
          fontsize=12, fontproperties=font0, color="b")
  ax.text( 1.1, 1.0, "[No.]  Date", ha="left", va="top", transform=ax.transAxes, \
          fontsize=12, fontproperties=font0, color="b")
  
  axrange = ax.get_xlim()
  ax.set_xlabel("UT [hours]")
  
  if axrange[1]-axrange[0] <= 1.0:
    jdhours = np.arange(0,3,1.0/24.)
    utchours = (np.arange(0,72,dtype=int)+12)%24
  else:
    jdhours = np.arange(0,3,1.0/12.)
    utchours = (np.arange(0,72, 2, dtype=int)+12)%24
  ax.set_xticks(jdhours)
  ax.set_xlim(axrange)
  ax.set_xticklabels(utchours, fontsize=18)  
  
  # Make ax2 responsible for "top" axis and "right" axis
  ax2 = ax.twin()
  # Set upper x ticks
  ax2.set_xticks(jdhours)
  ax2.set_xticklabels(utchours, fontsize=18)
  ax2.set_xlabel("UT [hours]")

  # Horizon angle for airmass
  airmass_ang = np.arange(5.,90.,5.)
  geo_airmass = airmass.airmassPP(90.-airmass_ang) 
  ax2.set_yticks(airmass_ang)
  airmassformat = []
  for t in range(geo_airmass.size):
    airmassformat.append("%2.2f" % geo_airmass[t])
  ax2.set_yticklabels(airmassformat, rotation=90)
  ax2.set_ylabel("Relative airmass", labelpad=32)
  ax2.tick_params(axis="y", pad=10, labelsize=10)
  plt.text(1.015,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \
           va='top', fontsize=10, rotation=90)

  ax22 = ax.twin()
  ax22.set_xticklabels([])  
  ax22.set_frame_on(True)
  ax22.patch.set_visible(False)
  ax22.yaxis.set_ticks_position('right')
  ax22.yaxis.set_label_position('right')
  ax22.spines['right'].set_position(('outward', 25))
  ax22.spines['right'].set_color('k')
  ax22.spines['right'].set_visible(True)
  airmass2 = np.array(map(lambda ang: airmass.airmassSpherical(90. - ang, allData[n]["Obs coord"][2]), \
                          airmass_ang))
  ax22.set_yticks(airmass_ang)
  airmassformat = []
  for t in range(airmass2.size): airmassformat.append("%2.2f" % airmass2[t])
  ax22.set_yticklabels(airmassformat, rotation=90)
  ax22.tick_params(axis="y", pad=10, labelsize=10)
  plt.text(1.045,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \
           fontsize=10, rotation=90)

  ax3 = ax.twiny()
  ax3.set_frame_on(True)
  ax3.patch.set_visible(False)
  ax3.xaxis.set_ticks_position('bottom')
  ax3.xaxis.set_label_position('bottom')
  ax3.spines['bottom'].set_position(('outward', 50))
  ax3.spines['bottom'].set_color('k')
  ax3.spines['bottom'].set_visible(True)

  ltime, ldiff = localtime.localTime(utchours, np.repeat(allData[n]["Obs coord"][0], len(utchours)))
  jdltime = jdhours - ldiff/24.
  ax3.set_xticks(jdltime)
  ax3.set_xticklabels(utchours)
  ax3.set_xlim([axrange[0],axrange[1]])
  ax3.set_xlabel("Local time [hours]")

  ax.yaxis.set_major_locator(MultipleLocator(15))
  ax.yaxis.set_minor_locator(MultipleLocator(5))
  yticks = ax.get_yticks()
  ytickformat = []
  for t in range(yticks.size): ytickformat.append(str(int(yticks[t]))+r"$^\circ$")
  ax.set_yticklabels(ytickformat, fontsize=20)
  ax.set_ylabel("Altitude", fontsize=18)
  yticksminor = ax.get_yticks(minor=True)
  ymind = np.where( yticksminor % 15. != 0. )[0]
  yticksminor = yticksminor[ymind]
  ax.set_yticks(yticksminor, minor=True)
  m_ytickformat = []
  for t in range(yticksminor.size): m_ytickformat.append(str(int(yticksminor[t]))+r"$^\circ$")
  ax.set_yticklabels(m_ytickformat, minor=True)
  
  ax.yaxis.grid(color='gray', linestyle='dashed')
  ax.yaxis.grid(color='gray', which="minor", linestyle='dotted')
  ax2.xaxis.grid(color='gray', linestyle='dotted')

  plt.text(0.5,0.95,"Transit visibility of "+allData[n]["Planet name"], \
           transform=fig.transFigure, ha='center', va='bottom', fontsize=20)

  if plotLegend:
    line1 = matplotlib.lines.Line2D((0,0),(1,1), color='#FDB813', linestyle="-", linewidth=2)
    line2 = matplotlib.lines.Line2D((0,0),(1,1), color='#BEBEBE', linestyle="-", linewidth=2)
    line3 = matplotlib.lines.Line2D((0,0),(1,1), color='k', linestyle="-", linewidth=2)
    line4 = matplotlib.lines.Line2D((0,0),(1,1), color='g', linestyle="-", linewidth=6, alpha=.3)

    if markTransit:
      lgd2 = plt.legend((line1,line2,line3, line4),("day","twilight","night","transit",), \
                        bbox_to_anchor=(0.88, 0.15), loc=2, borderaxespad=0.,prop={'size':12}, fancybox=True)
    else:
      lgd2 = plt.legend((line1,line2,line3),("day","twilight","night",), \
                        bbox_to_anchor=(0.88, 0.13), loc=2, borderaxespad=0.,prop={'size':12}, fancybox=True)
    lgd2.get_frame().set_alpha(.5)

  targetco = r"Target coordinates: (%8.4f$^\circ$, %8.4f$^\circ$)" % \
            (allData[n]["Star ra"], allData[n]["Star dec"])
  obsco = "Obs coord.: (%8.4f$^\circ$, %8.4f$^\circ$, %4d m)" % \
          (allData[n]["Obs coord"][0], allData[n]["Obs coord"][1], allData[n]["Obs coord"][2])
  plt.text(0.01,0.97, targetco, transform=fig.transFigure, ha='left', va='center', fontsize=10)
  plt.text(0.01,0.95, obsco, transform=fig.transFigure, ha='left', va='center', fontsize=10)
  
  if print2file:
    outfile = "transVis-"+allData[n]["Planet name"].replace(" ", "")+".png"
    plt.savefig(outfile, format="png", dpi=300)
  else:
    plt.show()
##
## first subgrid
##
##############################################

# EKG Axis
ax_ekg = plt.subplot(gs00[0, 0])
ekg_img = mpimg.imread('/home/jurek/git_repos/doctorate/Doktorat/graph/ekg.png')
ax_ekg.imshow(ekg_img) #, aspect='auto') #, origin='lower')
ax_ekg.set_axis_off()
ax_ekg.set_frame_on(False)
ax_ekg.autoscale_view(tight=True)

alignment = {'horizontalalignment':'left', 'verticalalignment':'center'}
text_fontsize = 20
font_1 = font_0.copy()
font_1.set_size(text_fontsize)
font_1.set_weight('bold')
ax_ekg.text(0.1, 0.1, u"EKG", fontproperties=font_1, **alignment)

####################################
ax_arrow_left = plt.subplot(gs00[0, 1])
ax_arrow_left.set_axis_off()
ax_arrow_left.set_frame_on(False)

arrow_left = mpatches.Arrow(0.0, 0.5, 0.9, 0.0, width=0.25, color="black", lw=4) #, label="Dane z EKG")
arrow_left.set_fill(False)
ax_arrow_left.add_patch(arrow_left)

#empty plot
create_empty_plot(gs00[0,2])
Exemple #43
0
def plot_multiple_roc(rocList, 
					title='', 
					labels=None, 
					include_baseline=True, 
					equal_aspect=True, 
					lengend_inside=True,
					file_name=None):
	""" Plots multiple ROC curves on the same chart. 
		Parameters:
			rocList: the list of ROCData objects
			title: The tile of the chart
			labels: The labels of each ROC curve
			include_baseline: if it's  True include the random baseline
			equal_aspect: keep equal aspect for all roc curves
	"""
	from matplotlib.font_manager import FontProperties
	font0 = FontProperties()
	cust_font = font0.copy()
	cust_font.set_family('arial')
	cust_font.set_size(12)
	
	pylab.clf()
	pylab.ylim((0,1))
	pylab.xlim((0,1))
	pylab.xticks(pylab.arange(0,1.1,.1))
	pylab.yticks(pylab.arange(0,1.1,.1))
	pylab.grid(True)
	if equal_aspect:
		cax = pylab.gca()
		cax.set_aspect('equal')
	pylab.tick_params(axis='both', which='major', labelsize=10)
	pylab.tick_params(axis='both', which='minor', labelsize=10)
			
	pylab.xlabel('False Positive Rate', fontproperties=cust_font) # 1 - True Negative Rate
	pylab.ylabel('True Positive Rate (Recall)', fontproperties=cust_font) # Sensitivity 

	pylab.title(title)
	
	if not labels: labels = [ '' for x in rocList]
	
	_remove_duplicate_styles(rocList)
	
	for ix, r in enumerate(rocList):
		pylab.plot([x[0] for x in r.derived_points], 
				[y[1] for y in r.derived_points], 
				r.linestyle, 
				linewidth=1, 
				label=labels[ix] + ', AUC: %.2f' % r.auc())
	
	if include_baseline:
		pylab.plot([0.0,1.0], [0.0, 1.0], 'k-', label= 'Random Guess')
	
#		pylab.annotate('Line of Perfect Classification', xy=(0, 1), xytext=(.1, .9),
#	            arrowprops=dict(facecolor='black', shrink=0.05))
#		pylab.annotate('Line of No-discrimination', xy=(0.55, 0.55), xytext=(.58, .5),
#	            arrowprops=dict(facecolor='black', shrink=0.05))
	
	if labels:
		if lengend_inside: # to place inside the plot 
			pylab.legend(loc='lower right', 
						prop={'size':12, 'family':'arial'})  
		else: # to place right outside 
			pylab.legend(bbox_to_anchor=(1.02, 1), loc=2, 
						borderaxespad=0., 
						prop={'size':9, 'family':'arial'}) 
		
	if file_name:
		pylab.savefig(file_name, dpi=700, bbox_inches='tight', pad_inches=0.1)
	else:
		pylab.show() 
import matplotlib.pyplot as plt

# My phone's internal storage usage by file type
file_types_and_usage = (
    ('image | jpeg', 1483),
    ('video | mp4', 678),
    ('audio | mpeg', 642),
    ('audio | ogg', 405),
    ('application | octet-stream', 103),
    ('other', 247),
)

# Prepare fonts
font1 = FontProperties()
font1.set_family('Source Han Sans TW')
font2 = font1.copy()
font2.set_size('small')

# Prepare subplots
fig1, ax1 = plt.subplots()

# Draw pie chart
_, texts, autotexts = ax1.pie(
    # sizes
    [ftu[1] for ftu in file_types_and_usage],
    labels=[ftu[0] for ftu in file_types_and_usage],
    autopct='%1.f%%',
    pctdistance=0.7,
    startangle=90
)
# Set equal aspect ratio to ensure that pie is drawn as a circle
    def __init__(self, chan, host, fold=19277, nmax=100,NORM=True,sequence=False):
        self.UPDATE = True
        self.color  = True
        
        self.channel  = chan
        self.t        = time.time()
        self.NORM     = NORM
        self.NMAX     = nmax
        self.fold     = fold
        self.shear    = 0.
        self.sequence = sequence
        self.vmin     = -125
        self.vmax     = 125
        
        ### To set the first name that has to be recorded ###
        try:
            L = C.getoutput('ls Image_*_DSA'+self.channel+' | sort -n').splitlines()
            temp = array([eval(L[i].split('_')[1]) for i in range(len(L))])
            self.flag_save = max(temp) + 1
        except:                      # nothing in the folder already
            self.flag_save = 1
        
        self.remove_len1 = 0 #6500  # 0 previously
        self.remove_len2 = 1 #12300 # 1 previously
        
        try:
            self.sock = vxi.Instrument(host)
            self.sock.write(':WAVeform:TYPE RAW')
            self.sock.write(':WAVEFORM:BYTEORDER LSBFirst')
            self.sock.write(':TIMEBASE:MODE MAIN')
            self.sock.write(':WAVEFORM:SOURCE ' + chan)
            self.sock.write(':WAVEFORM:FORMAT BYTE')
        except:
            print "\nWrong IP, Listening port or bad connection =>  Check cables first\n"
            sys.exit()
        
        if self.query(':'+self.channel+':DISP?')!='1\n':
            print "\nChannel "+chan[-1]+' is not active...\n'
            sys.exit()
        
        self.fig = figure(figsize=(16,7))
        
        ### trigger the scope for the first time ###
        self.single()
        self.load_data()
        self.update_tabs()
        self.Y0 = 0
        
        self.ax = axes([0.1,0.4,0.8,0.47])
        if not self.NORM:
            self.im = self.ax.imshow(self.folded_data, interpolation='nearest', aspect='auto',
		    origin='lower', vmin=self.vmin, vmax=self.vmax)
        else:
	        self.im = self.ax.imshow(self.folded_data, interpolation='nearest', aspect='auto',
		    origin='lower', vmin=self.folded_data.min(), vmax=self.folded_data.max())

        self.cursor = Cursor(self.ax, useblit=True, color='red', linewidth=2)

        self.axh = axes([0.1,0.05,0.8,0.2])
        self.hline, = self.axh.plot(self.folded_data[self.Y0,:])
        self.axh.set_xlim(0,len(self.folded_data[0,:]))
        if not self.NORM:
            self.axh.set_ylim(self.vmin, self.vmax)
        else:
            self.axh.set_ylim(self.folded_data.min(), self.folded_data.max())
        
        # create 'remove_len1' slider
        self.remove_len1_sliderax = axes([0.1,0.96,0.8,0.02])
        self.remove_len1_slider   = Slider(self.remove_len1_sliderax,'beg',0.,self.fold,self.remove_len1,'%d')
        self.remove_len1_slider.on_changed(self.update_tab)
        
        # create 'remove_len2' slider
        self.remove_len2_sliderax = axes([0.1,0.92,0.8,0.02])
        self.remove_len2_slider   = Slider(self.remove_len2_sliderax,'end',1.,self.fold,self.remove_len2,'%d')
        self.remove_len2_slider.on_changed(self.update_tab)
        
        # create 'shear' slider
        self.shear_sliderax = axes([0.1,0.88,0.8,0.02])
        self.shear_slider   = Slider(self.shear_sliderax,'Shear',-1,1,self.shear,'%1.2f')
        self.shear_slider.on_changed(self.update_shear)
        
        #if self.sequence:
        font0 = FontProperties()
        font1 = font0.copy()
        font1.set_weight('bold')
        mpl.pyplot.text(-1.1,-27,'Sequence mode:',fontsize=18,fontproperties=font1)
        mpl.pyplot.text(-0.75,-30,'"b" to toggle it then:\n      "y" to save\n      "n" to next',fontsize=18)
        mpl.pyplot.text(0.25,-27,'Useful keys:',fontsize=18,fontproperties=font1)
        mpl.pyplot.text(0.5,-31,'"v" to change vertical/colorscale\n " " to pause\n "S" to save trace and picture\n "q" to exit',fontsize=18)
        
        cid  = self.fig.canvas.mpl_connect('motion_notify_event', self.mousemove)
        cid2 = self.fig.canvas.mpl_connect('key_press_event', self.keypress)

        self.axe_toggledisplay  = self.fig.add_axes([0.43,0.27,0.14,0.1])
        self.plot_circle(0,0,2,fc='#00FF7F')
        mpl.pyplot.axis('off')
        
        gobject.idle_add(self.update_plot)
        show()
Exemple #46
0
def bubblePrices(city):

    irrelevantAttributes = [
        "City", "Monthly Pass", "Volkswagen Golf", "Toyota Corolla",
        "Basic Utilities", "Internet", "Fitness Club", "Tennis Court Rent",
        "Preschool Month", "Primary School Year", "Rent 1 Bedroom Center",
        "Rent 1 Bedroom Outside Center", "Rent 3 Bedrooms Center",
        "Rent 3 Bedrooms Outside Center", "Price m2 Center",
        "Price m2 Outside Center", "Average Monthly Salary After Tax",
        "Mortgage Interest Rate"
    ]
    fyrirspurn = "SELECT * FROM Prices where City = " + '"' + beforeComma(
        city) + '"'
    print(fyrirspurn)
    query = cur.execute(fyrirspurn)

    cols = [column[0] for column in query.description]

    results = pd.DataFrame.from_records(data=query.fetchall(), columns=cols)
    results.drop(columns=irrelevantAttributes, inplace=True)
    print(results.columns.values)

    values = list(results.loc[0, :])[0:]
    names = []

    j = 0
    for i in cols:
        if i not in irrelevantAttributes:
            names.append(i)

            j = j + 1

    fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'), figsize=(9, 7))

    fyrirspurn = "SELECT * FROM Prices where city = " + '"' + beforeComma(
        city) + '"'
    print(fyrirspurn)
    query = cur.execute(fyrirspurn)

    cols = [column[0] for column in query.description]

    results = pd.DataFrame.from_records(data=query.fetchall(), columns=cols)
    results.drop(columns=irrelevantAttributes, inplace=True)

    values = list(results.loc[0, :])[0:]
    names = []

    j = 0
    for i in cols:
        if i not in irrelevantAttributes:
            names.append(i)

            j = j + 1

    fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'), figsize=(9, 7))

    N = len(values)
    col = np.random.rand(N)
    print(col)
    end = math.ceil(math.sqrt(N))
    # þurfum að gera samsvörun
    step = end / N
    x = np.arange(0, end, step)
    hnitx = []
    for i in range(3, end + 2):
        for j in range(end):
            if (len(hnitx) == N):
                break
            hnitx.append(i)

    hnity = []
    for i in range(N):
        hnity.append(i % end)

    #plt.figure(figsize=(9,9))

    hnitx = [x + random.random() / 4 for x in hnitx]
    hnity = [y + random.random() / 4 for y in hnity]
    mynd = ax.scatter(hnitx,
                      hnity,
                      c=col,
                      alpha=0.5,
                      s=[x * 20 for x in values])
    plt.xlim((0.8, end + 2))

    plt.xticks([], [])
    plt.yticks([], [])

    fig.patch.set_visible(False)
    ax.axis('off')

    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = {
        'family': 'serif',
        'color': 'darkred',
        'weight': 'normal',
        'size': 13,
    }

    for label, x, y in zip(names, hnitx, hnity):
        r = random.random() * 2
        plt.text(x + 0.22,
                 y + 0.25,
                 label,
                 ha='right',
                 va='bottom',
                 fontdict=font)
        plt.plot([x + 0.22, x], [y + 0.25, y], 'k-', linewidth=0.5)
    # þarf að sjá

    font = {
        'family': 'serif',
        'color': 'black',
        'weight': 'normal',
        'size': 18,
    }
    ax.set_title("Bubble chart of prices of goods in " + city + " (area = €)",
                 fontdict=font)
    # vantar að staðfesta að röðin sé eins?

    tooltip = mpld3.plugins.PointLabelTooltip(
        mynd, labels=[str(x) + "€" for x in values])

    mpld3.plugins.connect(fig, tooltip)

    mpld3.show()
Exemple #47
0
width = 14000000
height = 10000000
#m = Basemap(width=width,height=height,\
#            resolution='c',projection='aeqd',\
#            lat_0=lat_0,lon_0=lon_0)
#m = Basemap(resolution='c',projection='aeqd',lat_0=lat_0,lon_0=lon_0)
#m = Basemap(width=width,height=height,\
#            resolution='c',projection='aea',\
#            lat_0=lat_0,lon_0=lon_0)
m = Basemap(resolution='c', projection='mbtfpq', lon_0=lon_0)
#m = Basemap(resolution='c',projection='moll',lon_0=lon_0)
#m = Basemap(resolution='c',projection='ortho',lon_0=lon_0,lat_0=lat_0)
#m = Basemap(resolution='c',projection='cyl',llcrnrlat=llcrnrlat,llcrnrlon=llcrnrlon,urcrnrlat=urcrnrlat,urcrnrlon=urcrnrlon)

p = FontProperties()
font1 = p.copy()
font1.set_size('small')

# draw coasts and fill continents.
m.drawcoastlines(linewidth=0.5)
m.fillcontinents()
m.drawparallels(arange(-80, 81, 10),
                labels=[1, 1, 0, 0],
                fontproperties=font1,
                labelstyle="+/-")
m.drawmeridians(arange(-180, 180, 20),
                labels=[0, 0, 0, 1],
                fontproperties=font1,
                labelstyle="+/-")
#m.bluemarble()
m.drawmapboundary()
Exemple #48
0
def drawing(ax, proj, CFIELD):
    # ==========================
    ''' Draw a 2D vector plot. Option of vectors or stream function'''

    __version__ = "1.0"
    __author__ = "Quim Ballabrerera"
    __date__ = "June 2017"

    import numpy as np
    import cartopy

    #EG Remember that CFIELD.VEL.PLOT.MESSAGE may serve to collect
    # messages

    fnt0 = FontProperties()
    font = fnt0.copy()
    font.set_size('x-large')

    if CFIELD.PLOT.DRAWING_MODE.get() == 2:
        # -------------------------------------------- STREAMFUNCTION
        CFIELD.PLOT.MESSAGE += "Plot STREAMFUNCTION" + str(CFIELD.PLOT.MESSAGE)

        if isinstance(proj, cartopy.crs.PlateCarree):
            #EG this call to quiver with zorder negative is needed to proceed
            #EG with the streamplot. Need further analysis. Cartopy 0.17
            #EG Matplotlib 3.1.1
            #ax.quiver(CFIELD.U.xx, CFIELD.U.yy, CFIELD.U.data, CFIELD.V.data,  \
            #              transform=proj,zorder=-1)
            ax.streamplot(CFIELD.U.xx, CFIELD.U.yy,                  \
                          CFIELD.U.data, CFIELD.V.data,              \
                          color=CFIELD.PLOT.STREAM_COLOR.get(),      \
                          linewidth=CFIELD.PLOT.STREAM_WIDTH.get(),  \
                          density=CFIELD.PLOT.STREAM_DENSITY.get(),  \
                          zorder=CFIELD.PLOT.ZORDER.get(),    \
                          transform=proj)
        else:
            CFIELD.PLOT.MESSAGE += 'VECTORPLOT:  WARNING: Streamplot only works with Cylindircal Projection'
            #print('VECTORPLOT:  WARNING: Streamplot only works with Cylindircal Projection')

    else:

        # Check if reprocessing data is required:
        if CFIELD.reprocess == False:
            if CFIELD.PLOT.GRID_MODE.get() != CFIELD.GRID_MODE_0:
                CFIELD.reprocess = True
            if CFIELD.PLOT.CURRENT_DX.get() != CFIELD.CURRENT_DX_0:
                CFIELD.reprocess = True
            if CFIELD.PLOT.CURRENT_DY.get() != CFIELD.CURRENT_DY_0:
                CFIELD.reprocess = True
            if CFIELD.PLOT.CURRENT_NX.get() != CFIELD.CURRENT_NX_0:
                CFIELD.reprocess = True
            if CFIELD.PLOT.CURRENT_NY.get() != CFIELD.CURRENT_NY_0:
                CFIELD.reprocess = True

        if CFIELD.reprocess:
            CFIELD.PLOT.MESSAGE += 'VECTORPLOT: processing data\n'
            CFIELD.reprocess = False
            CFIELD.GRID_MODE_0 = CFIELD.PLOT.GRID_MODE.get()
            CFIELD.CURRENT_DX_0 = CFIELD.PLOT.CURRENT_DX.get()
            CFIELD.CURRENT_DY_0 = CFIELD.PLOT.CURRENT_DY.get()
            CFIELD.CURRENT_NX_0 = CFIELD.PLOT.CURRENT_NX.get()
            CFIELD.CURRENT_NY_0 = CFIELD.PLOT.CURRENT_NY.get()

            if CFIELD.PLOT.GRID_MODE.get() == 0:
                CFIELD.PLOT.MESSAGE += "EG VECTORS: original or decimated grid"
                #print("EG VECTORS: original or decimated grid")
                dx = CFIELD.PLOT.CURRENT_DX.get()
                dy = CFIELD.PLOT.CURRENT_DY.get()
                CFIELD.xplt, CFIELD.yplt = CFIELD.U.xx[::dy, ::
                                                       dx], CFIELD.U.yy[::
                                                                        dy, ::
                                                                        dx]  # Grid stored in U
                CFIELD.uplt, CFIELD.vplt = CFIELD.U.data[::dy, ::
                                                         dx], CFIELD.V.data[::
                                                                            dy, ::
                                                                            dx]
            else:
                CFIELD.PLOT.MESSAGE += "EG VECTORS: fixed grid"
                #print("EG VECTORS: fixed grid")
                #EG The method "linear" in interpol.griddata is mandatory. Other
                #EG choices provides strange behaviour
                lonmin, lonmax, latmin, latmax = ax.get_extent()
                CFIELD.xplt = np.linspace(lonmin, lonmax,
                                          CFIELD.PLOT.CURRENT_NX.get())
                CFIELD.yplt = np.linspace(latmin, latmax,
                                          CFIELD.PLOT.CURRENT_NY.get())
                n_lon, n_lat = np.meshgrid(CFIELD.xplt, CFIELD.yplt)

                CFIELD.uplt = interpol.griddata((CFIELD.U.xx.flatten(),CFIELD.U.yy.flatten()), \
                          CFIELD.U.data.flatten(),(n_lon,n_lat), method='linear')
                CFIELD.vplt = interpol.griddata((CFIELD.U.xx.flatten(),CFIELD.U.yy.flatten()), \
                          CFIELD.V.data.flatten(),(n_lon,n_lat), method='linear')

            CFIELD.speed = np.sqrt(CFIELD.uplt**2 + CFIELD.vplt**2)
            CFIELD.reprocess = False

        if CFIELD.PLOT.DRAWING_MODE.get() == 0:
            # -------------------------------------------- VECTORS
            CFIELD.PLOT.MESSAGE += "EG VECTORPLOT: Arrows"
            #print("EG VECTORPLOT: Arrows")
            if CFIELD.PLOT.COLOR_BY_SPEED.get():
                quiver = ax.quiver(CFIELD.xplt,CFIELD.yplt,CFIELD.uplt,CFIELD.vplt, \
                              CFIELD.speed,                                         \
                              transform=proj,                                       \
                              color=CFIELD.PLOT.CURRENT_COLOR.get(),                \
                              width=CFIELD.PLOT.CURRENT_WIDTH.get(),                \
                              headwidth=CFIELD.PLOT.CURRENT_HEADWIDTH.get(),        \
                              headlength=CFIELD.PLOT.CURRENT_HEADLENGTH.get(),      \
                              scale=CFIELD.PLOT.CURRENT_SCALE.get(),                \
                              minlength=0,                                          \
                              alpha=CFIELD.PLOT.ALPHA.get(),                        \
                              zorder=CFIELD.PLOT.ZORDER.get())
            else:
                quiver = ax.quiver(CFIELD.xplt,CFIELD.yplt,CFIELD.uplt,CFIELD.vplt, \
                              transform=proj,                                       \
                              color=CFIELD.PLOT.CURRENT_COLOR.get(),                \
                              width=CFIELD.PLOT.CURRENT_WIDTH.get(),                \
                              headwidth=CFIELD.PLOT.CURRENT_HEADWIDTH.get(),        \
                              headlength=CFIELD.PLOT.CURRENT_HEADLENGTH.get(),      \
                              scale=CFIELD.PLOT.CURRENT_SCALE.get(),                \
                              minlength=0,                                          \
                              alpha=CFIELD.PLOT.ALPHA.get(),                        \
                              zorder=CFIELD.PLOT.ZORDER.get())

            if CFIELD.PLOT.KEY_SHOW.get():
                CFIELD.PLOT.KEY_OBJ = ax.quiverkey(
                    quiver,
                    CFIELD.PLOT.KEY_X.get(),
                    CFIELD.PLOT.KEY_Y.get(),
                    CFIELD.PLOT.KEY_VALUE.get(),
                    CFIELD.PLOT.KEY_LABEL.get(),
                    labelpos=CFIELD.PLOT.KEY_POS.get(),
                    coordinates='figure',
                    transform=proj,
                    labelcolor=CFIELD.PLOT.KEY_COLOR.get(),
                    fontproperties={'size': CFIELD.PLOT.KEY_SIZE.get()})

        elif CFIELD.PLOT.DRAWING_MODE.get() == 1:
            # -------------------------------------------- BARBS
            CFIELD.PLOT.MESSAGE += "EG VECTORPLOT: BARBS"
            #print("EG VECTORPLOT: BARBS")
            # Barb plot assumes knots
            knots = CFIELD.PLOT.BARB_SCALE.get()
            barb_increments = {
                'half': CFIELD.PLOT.BARB_HALF.get(),
                'full': CFIELD.PLOT.BARB_FULL.get(),
                'flag': CFIELD.PLOT.BARB_FLAG.get()
            }
            sizes = {
                'spacing': CFIELD.PLOT.BARB_SPACING.get(),
                'height': CFIELD.PLOT.BARB_HEIGHT.get(),
                'width': CFIELD.PLOT.BARB_WIDTH.get(),
                'emptybarb': CFIELD.PLOT.BARB_EMPTYBARB.get()
            }

            if CFIELD.PLOT.COLOR_BY_SPEED.get():
                speedk = knots * speed
                barbs = ax.barbs(CFIELD.xplt,
                                 CFIELD.yplt,
                                 knots * CFIELD.uplt,
                                 knots * CFIELD.vplt,
                                 speedk,
                                 pivot=CFIELD.PLOT.BARB_PIVOT.get(),
                                 length=CFIELD.PLOT.BARB_LENGTH.get(),
                                 linewidth=CFIELD.PLOT.BARB_LINEWIDTH.get(),
                                 barb_increments=barb_increments,
                                 sizes=sizes,
                                 transform=proj,
                                 alpha=CFIELD.PLOT.ALPHA.get(),
                                 zorder=CFIELD.PLOT.ZORDER.get())
            else:
                barbs = ax.barbs(CFIELD.xplt,
                                 CFIELD.yplt,
                                 knots * CFIELD.uplt,
                                 knots * CFIELD.vplt,
                                 pivot=CFIELD.PLOT.BARB_PIVOT.get(),
                                 length=CFIELD.PLOT.BARB_LENGTH.get(),
                                 barbcolor=CFIELD.PLOT.BARB_BARBCOLOR.get(),
                                 flagcolor=CFIELD.PLOT.BARB_FLAGCOLOR.get(),
                                 linewidth=CFIELD.PLOT.BARB_LINEWIDTH.get(),
                                 barb_increments=barb_increments,
                                 sizes=sizes,
                                 transform=proj,
                                 alpha=CFIELD.PLOT.ALPHA.get(),
                                 zorder=CFIELD.PLOT.ZORDER.get())
Exemple #49
0
if args.name_mappings is not None:
    name_mappings = json.loads(args.name_mappings)

fig, ax, rects, means, sigs = \
        graph.draw_from_data_frame(fs.expand_path_to_filelist(args.data), args.output, args.plot_type, args.filter,
                                   args.secondary_filter, args.attempt_auto_mapping, name_mappings, args)

font0 = FontProperties()

if args.plot_type == "bar":
    for i in range(len(rects)):
        for j in range(len(rects[i])):
            height = rects[i][j].get_height()
            if means[i][j] < 0:
                height = -height
            font = font0.copy()
            if sigs[i][j]:
                font.set_weight('bold')
            ax.text(rects[i][j].get_x()+rects[i][j].get_width()/2., 1.03*height, "%.1f"%means[i][j], ha='center',
                    va='center', fontproperties=font)

highest = [0] * len(means)

for i in range(len(means)):
    for j in range(len(means[i])):
        if means[i][j] > means[i][highest[i]]:
            highest[i] = j

for j in range(len(means[0])):
    for i in range(len(means)):
        # if sigs[i][j] and highest[i] == j:
Exemple #50
0
from matplotlib import patches
from matplotlib.font_manager import FontProperties


font24 = FontProperties()
font24.set_family('sans-serif')
font24.set_name('Helvetica')
font24.set_size(24)
font18 = font24.copy()
font18.set_size(18)
font36 = font24.copy()
font36.set_size(36)

outage0 = []
out_withd0 = []

with open("out_age.csv",'r') as filename1:
	for l in filename1:
		outage0.append(l.strip('\n').split(','))

with open("out_withd.csv",'r') as filename2:
	for l in filename2:
		out_withd0.append(l.strip('\n').split(','))


outage1 = array([(int(x),float(y),int(z)) for x,y,z in outage0[1:]])
out_withd1 = array([(int(x),float(y),int(z)) for x,y,z in out_withd0[2:]])


N = len(outage1)
xx = outage1[:,0]
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import glob
import calendar
from GPP_smooth_func import *
from matplotlib.font_manager import FontProperties

plt.rcParams["font.family"] = "Arial"
font0 = FontProperties()

font0 = FontProperties()
font_sub_title = font0.copy()
font_sub_title.set_size('12')
font_sub_title.set_weight('bold')

font_label = font0.copy()
font_label.set_size('11')
font_label.set_weight('bold')

font_tick = font0.copy()
font_tick.set_size('10')


def cm2inch(*tupl):
    inch = 2.54
    if isinstance(tupl[0], tuple):
        return tuple(i / inch for i in tupl[0])
def plot_data( x , data_nnfbp , data_standard , fom , zslice , path_common ):
    ##  Define figure enviroment
    fig = plt.figure( 1 , figsize=( 12 , 8 ) , dpi=100 )
    rect = fig.patch
    rect.set_facecolor('white')
    axescolor  = '#f6f6f6'
    ax = plt.subplot( 111 , axisbg=axescolor )

    
    ##  Font setting
    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = font1.copy()
    font.set_family('serif')
    rc('text',usetex=True)
    
    
    ##  Enable grid
    gridLineWidth = 0.2
    ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.05')

    
    ##  Marker setup
    colorArray = ['blue','red']
    markerArray = ['^','s','o','d']


    ##  Get title
    if fom == 'snr1':
        title = 'SNR analysis on ROI 1 of slice n. '
    elif fom == 'snr2':
        title = 'SNR analysis on ROI 2 of slice n. '
    elif fom == 'cnr':
        title = 'CNR analysis on ROI 1-2 of slice n. '
    elif fom == 'ssim':
        title = 'SSIM analysis on ROI of slice n. '
    elif fom == 'nmi':
        title = 'NMI analysis on ROI of slice n. ' 

    title += zslice


    ##  Get xlabel and ylabel
    xlabel = 'Total scan time ( s )'

    if fom == 'snr1':
        ylabel = 'SNR'
    elif fom == 'snr2':
        ylabel = 'SNR'
    elif fom == 'cnr':
        ylabel = 'CNR'
    elif fom == 'ssim':
        ylabel = 'SSIM'
    elif fom == 'nmi':
        ylabel = 'NMI'     


    ##  Tick setting
    fig.autofmt_xdate(bottom=0.18)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    ax.set_xticks( np.linspace(0.6, 1.2, 4) )


    ##  Set title and axis labeling
    plt.text(0.5, 1.06,title,horizontalalignment='center',fontsize=22,transform = ax.transAxes)
    plt.xlabel(xlabel, fontsize=22,position=(0.5,-0.2))
    plt.ylabel(ylabel, fontsize=22,position=(0.5,0.5))          
                                                               

    ##  Labels
    labels = [ '1.0 ms' , '1.5 ms' , '2.0 ms' , '4.0 ms' ]


    ##  Plot
    nalg = 2
    nset = 4
    
    plt.xlim([ 0.55 , 1.25 ])

    for i in range( nalg ):
        for j in range( nset ):
            if i == 0:
                y = data_nnfbp[j,:]
                label_aux = 'NNFBP'
            else:
                y = data_standard[j,:]
                label_aux = 'FBP'
        
            plt.plot( x , y , markerArray[j] , markersize=10.5, color=colorArray[i] ,
                      label= label_aux + ' - ' + labels[j] )
        
            plt.hold(True)


    ##  Add legend
    ax.set_position( [ 0.2 , 0.10 , 0.5 , 0.8 ] )
    ax.legend( loc='center left', bbox_to_anchor=(1, 0.5) )

    
    ##  Save plot and show it
    fileout = path_common + fom + '_analysis_slice' + zslice + '.png'
    plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' )

    plt.show()
Exemple #53
0
def bubbleIndices(cost, city):
    if (cost):
        fyrirspurn = "SELECT * FROM CostOfLivingIndex where city = " + '"' + city + '"'
    else:
        fyrirspurn = "SELECT * FROM QualityOfLifeIndex where city = " + '"' + city + '"'

    irrelevantAttributes = ["City", "Rank", "index"]

    ### allt fyrir neðan er sama og í Prices dæminu
    print(fyrirspurn)
    query = cur.execute(fyrirspurn)

    cols = [column[0] for column in query.description]

    results = pd.DataFrame.from_records(data=query.fetchall(), columns=cols)
    results.drop(columns=irrelevantAttributes, inplace=True)

    values = list(results.loc[0, :])[0:]
    names = []

    j = 0
    for i in cols:
        if i not in irrelevantAttributes:
            names.append(i)

            j = j + 1

    print(len(values))
    print(len(names))
    fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'), figsize=(9, 7))

    N = len(values)

    #col = np.arange(0.1,0.99,0.98/N)
    col = np.random.random_integers(0, N - 1)
    print(col)
    #print(len(col))
    colors = [
        'yellow', 'red', 'green', 'blue', 'black', 'purple', 'brown', 'pink'
    ]

    end = math.ceil(math.sqrt(N))
    # þurfum að gera samsvörun
    step = end / N
    x = np.arange(0, end, step)
    hnitx = []
    for i in range(1, end + 1):
        for j in range(end):
            if (len(hnitx) == N):
                break
            hnitx.append(i)

    hnity = []
    for i in range(N):
        hnity.append(i % end)

    #plt.figure(figsize=(9,9))

    # hnitx = [x + random.random()/4 for x in hnitx]
    # hnity = [y + random.random()/4 for y in hnity]
    print(hnitx)
    print(hnity)
    mynd = ax.scatter(hnitx,
                      hnity,
                      c=colors,
                      alpha=0.5,
                      s=[x * 20 for x in values])
    plt.xlim((0, end))
    plt.ylim((-1, end))

    plt.xticks([], [])
    plt.yticks([], [])

    fig.patch.set_visible(False)
    ax.axis('off')

    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    fonts = []
    for i in range(N):

        fonts.append({
            'family': 'serif',
            'color': colors[i],
            'weight': 'normal',
            'size': 10,
        })

    j = 0
    for label, x, y in zip(names, hnitx, hnity):

        plt.text(x + 0.22,
                 y + 0.25,
                 label,
                 ha='right',
                 va='bottom',
                 fontdict=fonts[j])
        j = j + 1
        #plt.plot([x+0.22,x], [y+0.25,y], 'k-', linewidth = 0.5)
    # þarf að sjá

    font = {
        'family': 'serif',
        'color': 'black',
        'weight': 'normal',
        'size': 18,
    }
    ax.set_title("Bubble chart of prices of goods in " + city + " (area = €)",
                 fontdict=font)
    # vantar að staðfesta að röðin sé eins?

    tooltip = mpld3.plugins.PointLabelTooltip(mynd, labels=values)

    mpld3.plugins.connect(fig, tooltip)

    mpld3.show()
def plot_data( data , dim , fom , path , n_files , ylim ):       
    ##  Define figure enviroment
    fig = plt.figure( 1 , figsize=( 12 , 8 ) , dpi=100 )
    rect = fig.patch
    rect.set_facecolor('white')
    axescolor  = '#f6f6f6'
    ax = plt.subplot( 111 , axisbg=axescolor )

    
    ##  Font setting
    font0 = FontProperties()
    font1 = font0.copy()
    font1.set_size('large')
    font = font1.copy()
    font.set_family('serif')
    rc('text',usetex=True)
    
    
    ##  Enable grid
    gridLineWidth = 0.2
    ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.05')

    
    ##  Marker setup
    colorArray = [ 'blue' , 'red' , 'green' , 'cyan' , 'magenta' , 'yellow' ,
                   'black' , 'red' , 'green' ]
    markerArray = [ 'o' , 'v' , '^' , '<' , '>' , 's' , 'p' , '*' , 'h' , 'H' , '+' , 'D' , 'd' , 
                    '|' , '_' , u'o' , u'v', u'^' , u'<' , u'>' , u'1' , u'2' , u'3' ,
                    u'4' , u'8' , u's' , u'p' , u'*' ]


    ##  Get title
    if dim == 0:
        title = 'Shepp-Logan 256 X 256 pixels'
        str_dim = 'pix0256'
    elif dim == 1:
        title = 'Shepp-Logan 512 X 512 pixels'
        str_dim = 'pix0512'
    elif dim == 2:
        title = 'Shepp-Logan 1024 X 1024 pixels'
        str_dim = 'pix1024'
    elif dim == 3:
        title = 'Shepp-Logan 2048 X 2048 pixels'
        str_dim = 'pix2048'


    ##  Get xlabel and ylabel
    xlabel = 'Forward projectors'

    if fom == 'psnr':
        ylabel = 'PSNR'
    elif fom == 'ssim':
        ylabel = 'SSIM'
    elif fom == 'nmi':
        ylabel = 'NMI'     


    ##  Tick setting
    fig.autofmt_xdate(bottom=0.18)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)


    ##  Set title and axis labeling
    plt.text(0.5, 1.02,title,horizontalalignment='center',fontsize=22,transform = ax.transAxes)
    plt.xlabel(xlabel, fontsize=22,position=(0.5,-0.2))
    plt.ylabel(ylabel, fontsize=22,position=(0.5,0.5))          
                                                               

    ##  Label
    x = np.arange( 1 , 7 , 1 )
    x_ticks = [ ' ' , 'NUFFT' , 'GRID-KB' , 'GRID-PSWF' , 'RT-BSPLINES' , 'RT-LIN' , 'RT-NN'  ] 



    ##  Plot
    if ylim is not None:
        plt.ylim([ ylim[0] , ylim[1] ]) 

    #ax.set_xticks( x_ticks )  
    ax.set_xticklabels( x_ticks ) 

    plt.xlim([ 0 , 7 ])

    for i in range( n_files ):
        y = data[i]

        plt.plot( x[i] , y , markerArray[i] , markersize=12, color=colorArray[i] )
        plt.hold(True)


    ##  Add legend
    ax.set_position( [ 0.2 , 0.12 , 0.5 , 0.8 ] )
    ax.legend( loc='center left', bbox_to_anchor=(1, 0.5) )

    
    ##  Save plot and show it
    fileout = path + fom + '_analysis_' + str_dim + '.png'
    plt.savefig( fileout , facecolor=fig.get_facecolor() , edgecolor='black' )

    plt.show()
width = 14000000
height = 10000000
# m = Basemap(width=width,height=height,\
#            resolution='c',projection='aeqd',\
#            lat_0=lat_0,lon_0=lon_0)
# m = Basemap(resolution='c',projection='aeqd',lat_0=lat_0,lon_0=lon_0)
# m = Basemap(width=width,height=height,\
#            resolution='c',projection='aea',\
#            lat_0=lat_0,lon_0=lon_0)
m = Basemap(resolution="c", projection="mbtfpq", lon_0=lon_0)
# m = Basemap(resolution='c',projection='moll',lon_0=lon_0)
# m = Basemap(resolution='c',projection='ortho',lon_0=lon_0,lat_0=lat_0)
# m = Basemap(resolution='c',projection='cyl',llcrnrlat=llcrnrlat,llcrnrlon=llcrnrlon,urcrnrlat=urcrnrlat,urcrnrlon=urcrnrlon)

p = FontProperties()
font1 = p.copy()
font1.set_size("small")

# draw coasts and fill continents.
m.drawcoastlines(linewidth=0.5)
# m.fillcontinents()
m.drawparallels(arange(-80, 81, 10), labels=[1, 1, 0, 0], fontproperties=font1, labelstyle="+/-")
m.drawmeridians(arange(-180, 180, 20), labels=[0, 0, 0, 1], fontproperties=font1, labelstyle="+/-")
m.drawmapboundary()

m.bluemarble()
m.drawmapboundary()

if arg1 < saa_switch_time:
    # Use the previous definitions
    # SAA 02
Exemple #56
0
def drawing(fig,ax,m,CFIELD):
# ======================================
  ''' Draw a 2D vector plot. Option of vectors or stream function'''

  __version__ = "1.0"
  __author__  = "Quim Ballabrerera"
  __date__    = "June 2017"

  import numpy as np
  fnt0 = FontProperties()
  font = fnt0.copy()
  font.set_size('x-large')

  if CFIELD.VEL.PLOT.DRAWING_MODE.get() == 0:
  # -------------------------------------------- VECTORS

    if CFIELD.VEL.PLOT.GRID_MODE.get() == 0:
      dx = CFIELD.VEL.PLOT.CURRENT_DX.get()
      dy = CFIELD.VEL.PLOT.CURRENT_DY.get()
      uplt,vplt,xplt,yplt = m.rotate_vector(CFIELD.VEL.u[::dy,::dx], \
                                            CFIELD.VEL.v[::dy,::dx], \
                                            CFIELD.lon[::dx],   \
                                            CFIELD.lat[::dy],   \
                                            returnxy=True)
    else:
      uplt,vplt,xplt,yplt = m.transform_vector(CFIELD.VEL.u, \
                                           CFIELD.VEL.v, \
                                           CFIELD.lon,   \
                                           CFIELD.lat,   \
                                           CFIELD.VEL.PLOT.CURRENT_NX.get(), \
                                           CFIELD.VEL.PLOT.CURRENT_NY.get(), \
                                           returnxy=True,                \
                                           masked=True)

    if CFIELD.VEL.PLOT.COLOR_BY_SPEED.get():
      speed = np.sqrt(uplt**2+vplt**2)
      quiver = m.quiver(xplt,yplt,uplt,vplt,speed,                       \
                      color=CFIELD.VEL.PLOT.CURRENT_COLOR.get(),           \
                      width=CFIELD.VEL.PLOT.CURRENT_WIDTH.get(),           \
                      headwidth=CFIELD.VEL.PLOT.CURRENT_HEADWIDTH.get(),   \
                      headlength=CFIELD.VEL.PLOT.CURRENT_HEADLENGTH.get(), \
                      scale=CFIELD.VEL.PLOT.CURRENT_SCALE.get(),
                      alpha=CFIELD.VEL.PLOT.CURRENT_ALPHA.get(),
                      zorder=CFIELD.VEL.PLOT.CURRENT_ZORDER.get(),
                      )

    else:
      quiver = m.quiver(xplt,yplt,uplt,vplt,                             \
                      color=CFIELD.VEL.PLOT.CURRENT_COLOR.get(),           \
                      width=CFIELD.VEL.PLOT.CURRENT_WIDTH.get(),           \
                      headwidth=CFIELD.VEL.PLOT.CURRENT_HEADWIDTH.get(),   \
                      headlength=CFIELD.VEL.PLOT.CURRENT_HEADLENGTH.get(), \
                      scale=CFIELD.VEL.PLOT.CURRENT_SCALE.get(),
                      alpha=CFIELD.VEL.PLOT.CURRENT_ALPHA.get(),
                      zorder=CFIELD.VEL.PLOT.CURRENT_ZORDER.get(),
                      )

    if CFIELD.VEL.PLOT.KEY_SHOW.get():
      CFIELD.VEL.PLOT.KEY_OBJ = ax.quiverkey(quiver,
                          CFIELD.VEL.PLOT.KEY_X.get(),
                          CFIELD.VEL.PLOT.KEY_Y.get(),
                          CFIELD.VEL.PLOT.KEY_VALUE.get(),
                          CFIELD.VEL.PLOT.KEY_LABEL.get(),
                          labelpos=CFIELD.VEL.PLOT.KEY_POS.get(),
                          coordinates='figure',
                          labelcolor=CFIELD.VEL.PLOT.KEY_COLOR.get(),
                          fontproperties={'size':
                                           CFIELD.VEL.PLOT.KEY_SIZE.get()},
                  )


  elif CFIELD.VEL.PLOT.DRAWING_MODE.get() == 1:
  # -------------------------------------------- BARBS

    # Barb plot assumes knots
    knots = CFIELD.VEL.PLOT.BARB_SCALE.get()
    barb_increments = {'half': CFIELD.VEL.PLOT.BARB_HALF.get(),
                       'full': CFIELD.VEL.PLOT.BARB_FULL.get(),
                       'flag': CFIELD.VEL.PLOT.BARB_FLAG.get()}
    sizes = {'spacing': CFIELD.VEL.PLOT.BARB_SPACING.get(),
             'height': CFIELD.VEL.PLOT.BARB_HEIGHT.get(),
             'width': CFIELD.VEL.PLOT.BARB_WIDTH.get(),
             'emptybarb': CFIELD.VEL.PLOT.BARB_EMPTYBARB.get()}


    if CFIELD.VEL.PLOT.GRID_MODE.get() == 0:
      dx = CFIELD.VEL.PLOT.CURRENT_DX.get()
      dy = CFIELD.VEL.PLOT.CURRENT_DY.get()
      uplt,vplt,xplt,yplt = m.rotate_vector(CFIELD.VEL.u[::dy,::dx], \
                                            CFIELD.VEL.v[::dy,::dx], \
                                            CFIELD.lon[::dx],   \
                                            CFIELD.lat[::dy],   \
                                            returnxy=True)
    else:
      uplt,vplt,xplt,yplt = m.transform_vector(CFIELD.VEL.u, \
                                           CFIELD.VEL.v, \
                                           CFIELD.lon,   \
                                           CFIELD.lat,   \
                                           CFIELD.VEL.PLOT.CURRENT_NX.get(), \
                                           CFIELD.VEL.PLOT.CURRENT_NY.get(), \
                                           returnxy=True,                \
                                           masked=True)

      if CFIELD.VEL.PLOT.COLOR_BY_SPEED.get():
        speed = knots*np.sqrt(uplt**2+vplt**2)
        barbs = m.barbs(xplt,yplt,knots*uplt,knots*vplt,speed,
                        pivot=CFIELD.VEL.PLOT.BARB_PIVOT.get(),
                        length=CFIELD.VEL.PLOT.BARB_LENGTH.get(),
                        linewidth=CFIELD.VEL.PLOT.BARB_LINEWIDTH.get(),
                        barb_increments=barb_increments,
                        sizes=sizes,
                        alpha=CFIELD.VEL.PLOT.BARB_ALPHA.get(),
                        zorder=CFIELD.VEL.PLOT.BARB_ZORDER.get(),
                       )
      else:
        barbs = m.barbs(xplt,yplt,knots*uplt,knots*vplt,
                        pivot=CFIELD.VEL.PLOT.BARB_PIVOT.get(),
                        length=CFIELD.VEL.PLOT.BARB_LENGTH.get(),
                        barbcolor=CFIELD.VEL.PLOT.BARB_BARBCOLOR.get(),
                        flagcolor=CFIELD.VEL.PLOT.BARB_FLAGCOLOR.get(),
                        barb_increments=barb_increments,
                        sizes=sizes,
                        linewidth=CFIELD.VEL.PLOT.BARB_LINEWIDTH.get(),
                        alpha=CFIELD.VEL.PLOT.BARB_ALPHA.get(),
                        zorder=CFIELD.VEL.PLOT.BARB_ZORDER.get(),
                       )


  elif CFIELD.VEL.PLOT.DRAWING_MODE.get() == 2:
  # -------------------------------------------- STREAMFUNCTION 
    if m.projparams['proj'] == 'cyl':
      # -------------------
      ax.streamplot(CFIELD.xx, CFIELD.yy, CFIELD.VEL.u, CFIELD.VEL.v,      \
                   color=CFIELD.VEL.PLOT.STREAM_COLOR.get(),           \
                   linewidth=CFIELD.VEL.PLOT.STREAM_WIDTH.get(),       \
                   zorder=CFIELD.VEL.PLOT.STREAM_ZORDER.get(),       \
                   density=CFIELD.VEL.PLOT.STREAM_DENSITY.get())
    else:
      print('WARNING: Streamplot only works with Cylindircal Projection') 
Exemple #57
0
See :doc:`fonts_demo_kw` to achieve the same effect using kwargs.
"""

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt

plt.subplot(111, facecolor='w')

font0 = FontProperties()
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options

families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']

font1 = font0.copy()
font1.set_size('large')

t = plt.text(-0.8, 0.9, 'family', fontproperties=font1,
             **alignment)

yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]

for k, family in enumerate(families):
    font = font0.copy()
    font.set_family(family)
    t = plt.text(-0.8, yp[k], family, fontproperties=font,
                 **alignment)

# Show style options
Exemple #58
0
def plot_ref_genome(start_points,lens,cycle,total_length_with_spacing,segSeqD,imputed_status,label_segs=True):
    font0 = FontProperties()
    seg_posns = []
    global_start = total_length_with_spacing*(global_rot/360.0)
    for ind,sp in enumerate(start_points):
        start_point = int(global_start - sp)
        seg_coord_tup = segSeqD[cycle[ind][0]]
        start_angle, end_angle, _ = start_end_angle(start_point,start_point - lens[ind],total_length_with_spacing)
        
        #makes the reference genome wedges    
        patches.append(mpatches.Wedge((0,0), outer_bar, end_angle, start_angle, width=bar_width))
        chrom = segSeqD[cycle[ind][0]][0]
        f_color_v.append(chromosome_colors[chrom])
        e_color_v.append('grey')
        lw_v.append(0.2)
        
        #makes the ticks on the reference genome wedges
        if cycle[ind][1] == "+":
            posns = zip(range(seg_coord_tup[1],seg_coord_tup[2]+1),np.arange(start_point,start_point-lens[ind]-1,-1))
        else:
            posns = zip(np.arange(seg_coord_tup[2],seg_coord_tup[1]-1,-1),np.arange(start_point,start_point-lens[ind]-1,-1))

        tick_freq = max(10000,10000*int(np.floor(total_length_with_spacing/1000000)))
        for j in posns:
            if j[0] % tick_freq == 0:
                text_angle = j[1]/total_length_with_spacing*360
                x,y = pol2cart(outer_bar,(text_angle/360*2*np.pi))
                x_t,y_t = pol2cart(outer_bar + 0.2,(text_angle/360*2*np.pi))
                ax.plot([x,x_t],[y,y_t],color='grey',linewidth=0.2)
                
                if (abs(text_angle) > 90 and abs(text_angle) < 360):
                    text_angle-=180
                    ha = "right"
                    txt = str(int(round((j[0])/10000))) + " "

                else:
                    ha = "left"
                    txt = " " + str(int(round((j[0])/10000)))

                ax.text(x_t,y_t,txt,color='grey',rotation=text_angle,
                ha=ha,fontsize=4,rotation_mode='anchor')
    
        gene_tree = parse_genes(seg_coord_tup[0])
        relGenes = rel_genes(gene_tree,seg_coord_tup)
        #plot the gene track
        plot_gene_track(start_point,relGenes,seg_coord_tup,total_length_with_spacing,cycle[ind][1])

        #label the segments by number in cycle
        mid_sp = start_point - lens[ind]/2
        text_angle = mid_sp/total_length*360.
        x,y = pol2cart(outer_bar-0.9,(text_angle/360.*2.*np.pi))
        font = font0.copy()
        if imputed_status[ind]:
            font.set_style('italic')
            font.set_weight('bold')

        if (abs(text_angle) > 90 and abs(text_angle) < 360):
            text_angle-=180
            ha = "left"

        else:
            ha = "right"

        if label_segs:
            ax.text(x,y,cycle[ind][0]+cycle[ind][1],color='grey',rotation=text_angle,
                ha=ha,fontsize=5,fontproperties=font,rotation_mode='anchor')