コード例 #1
0
ファイル: visualization.py プロジェクト: fonhorst/heft
def _draw_popsstat_component(data, name, title, ylabel, default_value=-1):
     ## TODO: remake it with acquaring figure and subplot from the function arguments
    colors = ['r', 'g', 'b']

    plt.grid(True)
    ax = plt.gca()
    ax.set_xlim(0, len(points))
    ax.set_xscale('linear')
    plt.xticks(range(0, len(points)))
    ax.set_xticklabels(points)
    ax.set_title(title)
    ax.set_ylabel(ylabel)
    plt.setp(plt.xticks()[1], rotation=30, ha='right')

    species = sorted(data["metainfo"]["species"])
    pcolors = {s: c for s, c in zip(species, colors)}

    gens = sorted(data["iterations"], key=lambda x: x["gen"])
    values = {s: [(points.index(gen["gen"]), gen["popsstat"][0][s].get(name, default_value))
                  for gen in gens if gen["gen"] in points]
              for s in species}

    plotted = []
    labels = []
    for s, vals in values.items():
        plt.plot([x[0] for x in vals], [x[1] for x in vals], "-{0}x".format(pcolors[s]))
        plotted.append(Rectangle((0, 0), 1, 1, fc=pcolors[s]))
        labels.append(s)

    plt.legend(plotted, labels)
    pass
コード例 #2
0
ファイル: qvp_boxpol.py プロジェクト: kmuehlbauer/qvp
def add_plot(mom, cfg):
    ax = mom['ax']
    levels = mom['levels']
    if cfg['contour']:
        im = ax.contourf(mom['data'], levels=levels,
                         colors=cfg['colors'], origin='lower', axis='equal',
                         extent=[cfg['dt_start'], cfg['dt_stop'],
                                 -0.11, cfg['beam_height'][-1]])
    else:
        cmap = ListedColormap(cfg['colors'])  # , name='')
        norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
        im = ax.pcolormesh(cfg['X'], cfg['Y'], mom['data'], cmap=cmap, norm=norm)

    ax.set_ylim(0, 13)
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%H:%M'))
    ax.xaxis.set_major_locator(mdates.HourLocator())
    ax.xaxis.set_minor_formatter(mdates.DateFormatter('%M'))
    ax.xaxis.set_minor_locator(
        mdates.MinuteLocator(byminute=(15, 30, 45, 60)))
    ax.grid()
    ax.set_ylabel('Height (km)')
    ax.set_xlabel('Time (UTC)')

    cb = mom['fig'].colorbar(im, orientation='vertical', pad=0.018, aspect=35)
    cb.outline.set_visible(False)
    cbarytks = plt.getp(cb.ax.axes, 'yticklines')
    plt.setp(cbarytks, visible=False)
    cb.set_ticks(levels[0:-1])
    cb.set_ticklabels(["%.2f" % lev for lev in levels[0:-1]])
    cb.set_label(mom['cb_label'])
コード例 #3
0
ファイル: rootmovie.py プロジェクト: hedgefair/viz
def rootmov( numframes, degree, bins, dpi):
        #Main loop for making frame images
        for frame in range(1,numframes + 1):
               realy = list()
               imagy = list()
               percent = 1.0 * frame / numframes
               # Find the roots of all polynomials of given degree as coefficients vary.
	       for group in product(pathcoeff(percent),repeat=degree):
                        rootie = np.roots(group)
                        for rooter in list(rootie):
                                if rooter.imag != 0:
                                        realy.append(rooter.real)
                                        imagy.append(- rooter.imag)
               # Make histogram of roots.
               H, xedges, yedges = np.histogram2d(realy,imagy, bins=bins)
               H = np.log1p( 1 / (1 + H ) )
               # Configure and save an image of the histogram.
               fig=plt.figure( facecolor='k', edgecolor='k')
               ax=plt.gca()
               plt.setp(ax, frame_on=True)
               plt.setp(ax.get_xticklabels(), visible=False)
               plt.setp(ax.get_yticklabels(), visible=False)
               plt.setp(ax.get_xticklines(), visible=False)
               plt.setp(ax.get_yticklines(), visible=False)
               plt.imshow(H,interpolation='bicubic',extent=[0,1000,0,600], cmap=dynacm( percent ) )
               plt.savefig("root_test{:04}.png".format(frame),dpi=dpi, facecolor='k', edgecolor='k', bbox_inches='tight')
               ax.clear()
               plt.close(fig)
コード例 #4
0
ファイル: logsearch_v2.py プロジェクト: minhouse/python-dev
def graph(excel, dflist):
    fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(16, 9), sharex=False, sharey=False)
    #fig.subplots_adjust(wspace=0, hspace=0)
    fig.subplots_adjust(hspace=0.5, left=0.5, right=0.9, bottom=0.01, top=0.95)
    fig.autofmt_xdate()
    plt.setp(axes, xticklabels=[], yticks=[])

    for i, j in enumerate(dflist):
        df = pd.read_excel('C:/Users/TokuharM/Desktop/Python_Scripts/%s' %excel, sheetname ='%s' % j, na_values=['NA'],parse_dates=['date'])
        df.sort_index(by = ["date"])

        x = df[["date"]]
        y = df[["errors"]]

        ax = fig.add_subplot(4,3,i+1)
        #ax = fig.add_subplot(i/3+1,i%3+1,1)
        ax.plot(x, y, "-o") #axに対してラベル幅などの調整を行う

        if len(x) > 0:
            days = mdates.DayLocator()
            daysFmt = mdates.DateFormatter('%m-%d')
            ax.xaxis.set_major_locator(days)
            ax.xaxis.set_major_formatter(daysFmt)
            ax.xaxis.set_ticks(pd.date_range(x.iloc[1,0], x.iloc[-1,0], freq='7d'))
            #ax.set_xlabel('Date')
            ax.set_ylabel('Errors')
            #ax.set_xticklabels('off')
            #ax.set_yticklabels('off')
            ax.grid()
            plt.xticks(rotation=30, fontsize='8')
            plt.yticks(range(0,400,30), fontsize='8')
            plt.axis('tight')
            ax.set_title(j, fontsize='10')
    plt.tight_layout(pad=1.0, w_pad=1.0, h_pad=1.0)
    plt.show()
コード例 #5
0
	def barPlot(self, datalist, threshold, figname):

		tally = self.geneCount(datalist)

		#Limit the items plotted to those over 1% of the read mass
		geneplot = defaultdict()
		for g, n in tally.iteritems():
			if n > int(sum(tally.values())*threshold):
				geneplot[g] = n

		#Get plotting values
		olist = OrderedDict(sorted(geneplot.items(),key=lambda t: t[0]))
		summe = sum(olist.values())
		freq = [float(x)/float(summe) for x in olist.values()]
		
		#Create plot
		fig = plt.figure()
		width = .35
		ind = np.arange(len(geneplot.keys()))
		plt.bar(ind, freq)
		plt.xticks(ind + width, geneplot.keys())
		locs, labels = plt.xticks() 
		plt.setp(labels, rotation=90)
		plt.show()

		fig.savefig(figname)
		print("Saved bar plot as: "+figname)
コード例 #6
0
def Bplot(data,label,ylabel,trueVal):
    fig = plt.figure(dpi=600)
    ax = plt.subplot(111)
    bp = plt.boxplot(data, notch=0, sym='o', vert=1, whis=1.5,patch_artist=True)
    plt.setp(bp['boxes'], color='black',linewidth=1.5,facecolor='darkkhaki')
    plt.setp(bp['whiskers'], color='black',linewidth=1.5)
    plt.setp(bp['caps'], color='black',linewidth=1.5)
    plt.setp(bp['medians'], color='darkgreen',linewidth=1.5)
    plt.setp(bp['fliers'], color='grey', marker='o')
    ax.axhline(y=trueVal,xmin=0,xmax=1,c="r",linewidth=2.0,zorder=0,linestyle='--')

    ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.8)
    ax.set_axisbelow(True)
    ax.set_ylabel(ylabel,fontsize = 24)
#     ax.set_xlabel(r'Variability',fontsize = 24)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(18)
    ax.set_xticklabels(label,fontsize=18)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
       
    for i in range(len(data)):
        med = bp['medians'][i]
        plt.plot([np.average(med.get_xdata())], [np.average(data[i])],color='r', marker='*', markeredgecolor='k',markersize=10,label="Mean")
    
    fig.tight_layout()
    savingTitle = ylabel.translate(None,'${}')
    fig.savefig(''.join(['Plots/',funcFolder,'/Boxplots/%s.eps'])%(savingTitle),format='eps')
コード例 #7
0
ファイル: hasy_tools.py プロジェクト: mehdidc/data_tools
def _analyze_class_distribution(csv_filepath,
                                max_data=1000,
                                bin_size=25):
    """Plot the distribution of training data over graphs."""
    symbol_id2index = generate_index(csv_filepath)
    index2symbol_id = {}
    for index, symbol_id in symbol_id2index.items():
        index2symbol_id[symbol_id] = index
    data, y = load_images(csv_filepath, symbol_id2index, one_hot=False)

    data = {}
    for el in y:
        if el in data:
            data[el] += 1
        else:
            data[el] = 1
    classes = data
    images = len(y)

    # Create plot
    print("Classes: %i" % len(classes))
    print("Images: %i" % images)

    class_counts = sorted([count for _, count in classes.items()])
    print("\tmin: %i" % min(class_counts))

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    # plt.title('HASY training data distribution')
    plt.xlabel('Amount of available testing images')
    plt.ylabel('Number of classes')

    # Where we want the ticks, in pixel locations
    ticks = [int(el) for el in list(np.linspace(0, 200, 21))]
    # What those pixel locations correspond to in data coordinates.
    # Also set the float format here
    ax1.set_xticks(ticks)
    labels = ax1.get_xticklabels()
    plt.setp(labels, rotation=30)

    min_examples = 0
    ax1.hist(class_counts, bins=range(min_examples, max_data + 1, bin_size))
    # plt.show()
    filename = '{}.pdf'.format('data-dist')
    plt.savefig(filename)
    logging.info("Plot has been saved as {}".format(filename))

    symbolid2latex = _get_symbolid2latex()

    top10 = sorted(classes.items(), key=lambda n: n[1], reverse=True)[:10]
    top10_data = 0
    for index, count in top10:
        print("\t%s:\t%i" % (symbolid2latex[index2symbol_id[index]], count))
        top10_data += count
    total_data = sum([count for index, count in classes.items()])
    print("Top-10 has %i training data (%0.2f%% of total)" %
          (top10_data, float(top10_data) * 100.0 / total_data))
    print("%i classes have more than %i data items." %
          (sum([1 for _, count in classes.items() if count > max_data]),
           max_data))
コード例 #8
0
ファイル: make_series.py プロジェクト: bewest/diabetes
  def get_axis( ax, limit ):
    xmin, xmax = limit
    ax.set_xlim( [ xmin, xmax ] )

    ax.grid(True)
    #ax.set_ylim( [ ts.value.min( ) *.85 , 600 ] )
    #ax.set_xlabel('time')

    majorLocator   = dates.DayLocator( )
    majorFormatter = dates.AutoDateFormatter( majorLocator )

    minorLocator   = dates.HourLocator( interval=6 )
    minorFormatter = dates.AutoDateFormatter( minorLocator )

    #ax.xaxis.set_major_locator(majorLocator)
    #ax.xaxis.set_major_formatter(majorFormatter)

    ax.xaxis.set_minor_locator(minorLocator)
    ax.xaxis.set_minor_formatter(minorFormatter)

    labels = ax.get_xminorticklabels()
    plt.setp(labels, rotation=30, fontsize='small')
    plt.setp(ax.get_xmajorticklabels(), rotation=30, fontsize='medium')

    xmin, xmax = ax.get_xlim( )
    
    log.info( pformat( {
      'xlim': [ dates.num2date( xmin ), dates.num2date( xmax ) ],
      'xticks': dates.num2date( ax.get_xticks( ) ),
    } ) )
コード例 #9
0
ファイル: make_series.py プロジェクト: bewest/diabetes
def plot_glucose_stems( ax, ts ):
  # visualize glucose using stems
  markers, stems, baselines = ax.stem( ts.time, ts.value,
           linefmt='b:' )
  plt.setp( markers, color='red', linewidth=.5,
            marker='o' )
  plt.setp( baselines, marker='None' ) 
コード例 #10
0
ファイル: matrix.py プロジェクト: amitkr492/MACHINE_LEARNING
    def plot_matrix(self, colorbar_kws, xind, yind, **kws):
        self.data2d = self.data2d.iloc[yind, xind]
        self.mask = self.mask.iloc[yind, xind]

        # Try to reorganize specified tick labels, if provided
        xtl = kws.pop("xticklabels", "auto")
        try:
            xtl = np.asarray(xtl)[xind]
        except (TypeError, IndexError):
            pass
        ytl = kws.pop("yticklabels", "auto")
        try:
            ytl = np.asarray(ytl)[yind]
        except (TypeError, IndexError):
            pass

        heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.cax,
                cbar_kws=colorbar_kws, mask=self.mask,
                xticklabels=xtl, yticklabels=ytl, **kws)

        ytl = self.ax_heatmap.get_yticklabels()
        ytl_rot = None if not ytl else ytl[0].get_rotation()
        self.ax_heatmap.yaxis.set_ticks_position('right')
        self.ax_heatmap.yaxis.set_label_position('right')
        if ytl_rot is not None:
            ytl = self.ax_heatmap.get_yticklabels()
            plt.setp(ytl, rotation=ytl_rot)
コード例 #11
0
ファイル: report_figs.py プロジェクト: aleaf/Figures
    def legend(self, ax, handles, labels, **kwargs):
        '''Make a legend, following guidelines in USGS Illustration Standards, p. 14

        ax : matplotlib.pyplot axis object
        handles : list
            matplotlib.pyplot handles for each plot
        labels : list
            labels for each plot
        kwargs : dict
            keyword arguments to matplotlib.pyplot.legend()
        '''

        lgkwargs = {'title': 'EXPLANATION',
                    'fontsize': self.legend_headingsize,
                    'frameon': False,
                    'loc': 8,
                    'bbox_to_anchor': (0.5, -0.25)}
        lgkwargs.update(kwargs)

        mpl.rcParams['font.family'] = self.title_font


        lg = ax.legend(handles, labels, **lgkwargs)

        plt.setp(lg.get_title(), fontsize=self.legend_titlesize)
        #reset rcParams back to default
        mpl.rcParams['font.family'] = self.default_font
        return lg
コード例 #12
0
ファイル: plotResults.py プロジェクト: tunino91/dpOptTrans
def PlotErrBoxPlot(x, y, delta, ax, showXTicks):
  if x.size < 1:
    return
  ids = np.floor((x)/delta).astype(np.int)
  data = []
  for i in range(ids.min(), ids.max()+1):
    if (ids==i).any():
      data.append(y[ids==i])
  bp = plt.boxplot(data)
#  plt.plot(x,y,'.', color=c1, alpha=0.3)
  # set xticks
  if showXTicks:
    ticks = np.floor((np.arange(ids.min(), ids.max()+1)+0.5)*delta).astype(np.int)
    if np.unique(ticks).size < ticks.size:
      ticks = np.floor((np.arange(ids.min(), ids.max()+1)+0.5)*delta*10.)/10.
    xtickNames = plt.setp(ax, xticklabels=ticks)
    plt.setp(xtickNames, rotation=45)
  else:
    plt.setp(ax.get_xticklabels(), visible=False) 
  for box in bp["boxes"]:
    box.set(color=c1)
    #box.set(facecolor=c1)
  for whisker in bp["whiskers"]:
    whisker.set(color=c1)
  for cap in bp["caps"]:
    cap.set(color=c1)
  for median in bp["medians"]:
    median.set(color=c2)
  for flier in bp["fliers"]:
    flier.set(color=c3, marker=".", alpha=0.15) #,s=6)
コード例 #13
0
ファイル: plotResults.py プロジェクト: tunino91/dpOptTrans
def PlotScatter(x, y, delta, ax, showXTicks):
  if x.size < 1:
    return
  plt.plot(x,y,'.', color=c1, alpha=0.3)
  # set xticks
  if not showXTicks:
    plt.setp(ax.get_xticklabels(), visible=False) 
コード例 #14
0
def plot(lookup):
        data = []
        for iiDiameter in sorted(lookup.keys()):
                data.append(lookup[iiDiameter])
        plt.boxplot(data, sym='')
        plt.setp(plt.gca(),'xticklabels',sorted(lookup.keys()))
        plt.show()
コード例 #15
0
def demo_locatable_axes_hard(fig1):

    from mpl_toolkits.axes_grid1 import SubplotDivider, LocatableAxes, Size

    divider = SubplotDivider(fig1, 2, 2, 2, aspect=True)

    # axes for image
    ax = LocatableAxes(fig1, divider.get_position())

    # axes for colorbar
    ax_cb = LocatableAxes(fig1, divider.get_position())

    h = [Size.AxesX(ax), Size.Fixed(0.05), Size.Fixed(0.2)]  # main axes  # padding, 0.1 inch  # colorbar, 0.3 inch

    v = [Size.AxesY(ax)]

    divider.set_horizontal(h)
    divider.set_vertical(v)

    ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
    ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))

    fig1.add_axes(ax)
    fig1.add_axes(ax_cb)

    ax_cb.axis["left"].toggle(all=False)
    ax_cb.axis["right"].toggle(ticks=True)

    Z, extent = get_demo_image()

    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    plt.colorbar(im, cax=ax_cb)
    plt.setp(ax_cb.get_yticklabels(), visible=False)
コード例 #16
0
def candlestickGraph(start, end, stock):
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %y')  # e.g., Jan 12016
    dayFormatter = DateFormatter('%d')

    quotes = quotes_historical_yahoo_ohlc(stock, start, end)

    if len(quotes) == 0:
        raise SystemExit
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.1)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick_ohlc(ax, quotes, width=.6, colorup='#77d879', colordown='#db3f3f', alpha=0.65)

    ax.xaxis.set_major_locator(mticker.MaxNLocator(10))


    for label in ax.xaxis.get_ticklabels():
            label.set_rotation(45)

    ax.xaxis_date()

    plt.setp(plt.gca().get_xticklabels(), rotation=45)

    plt.show()
コード例 #17
0
ファイル: photo.py プロジェクト: shch/weibo
def trendPicture(rt,comment):
     
    colorList = ['b','g','r','c','m','y','k']
 
    threadList = []
    for i in range(len(rt)):
	threadList.append(i)
   
    dataList1 = [int(x) for x in rt]
    dataList2 = [int(x) for x in comment]
   
    string = str(len(dataList1)) + u'条微博趋势图'
    plt.title(string)

    
    lines = []

    titles = []

   
    line1 = plt.plot(threadList, dataList1)
    plt.setp(line1, color=colorList[0], linewidth=2.0)
    titles.append(u'转发')
    lines.append(line1)

   
    line2 = plt.plot(threadList, dataList2)
    plt.setp(line2, color=colorList[1], linewidth=2.0)
    titles.append(u'评论')
    lines.append(line2)

    plt.legend(lines, titles)
    plt.show()
コード例 #18
0
def plot_bold_signal(timeseries, x, y):
	# plots timeseries of two given nodes in a specific time interval
	
	v1  = timeseries[:, x]
	v2  = timeseries[:, y]
	
	T   = len(v1)	
	time = np.linspace(0, T-1, T) / float(60000)
	
	[R_pearson , p_value] = sistat.pearsonr(v1 , v2)
	
	## if the given signal downsampled :
	#time_bds = np.arange(0,  530,  float(530)/len(v1) )/float(60)
	#pl.plot(time_bds, v1, 'r',label=('node '+str(x)))
	#pl.plot(time_bds, v2, 'b',label=('node '+str(y)))
	
	# if no downsampling :

	fig , ax = pl.subplots(figsize=(25, 5.5))
	pl.subplots_adjust(left=0.08, right=0.98, top=0.94, bottom=0.20)

	pl.plot(time, v1, 'm', label=('$u_{' + str(x+1) + '}(t)$'))
	pl.plot(time, v2, 'g', label=('$u_{' + str(y+1) + '}(t)$'))
	pl.setp(pl.gca().get_xticklabels(), fontsize = 30)
	pl.setp(pl.gca().get_yticklabels(), fontsize = 30)
	
	#ax.set_ylim(-v2.max()-0.05, v2.max()+0.05)
	ax.set_ylim(-0.6, 0.6)
	
	pl.legend(prop={'size':35})

	pl.xlabel('t [min]', fontsize=30)
	pl.ylabel('BOLD % change' ,fontsize=40)
	
	return	
コード例 #19
0
def set_axis_properties(p,metric,varying_parameter,group):

    #Set major x-axis label
    plt.xlabel(xlabel_names[varying_parameter])

    #Set x-axis scale
    xscale_args = xscale_arguments[(metric,varying_parameter)]
    plt.xscale(xscale_args[0],**xscale_args[1])

    #Set x-axis tick labels
    #Get tick values
    ticks = list(sp.unique(group[varying_parameter]))

    #If an item is not in the tick dictionary for the bar plot, add it
    if pltkind[(metric,varying_parameter)] is 'bar':
        for item in ticks:
            if item not in varying_xlabels[varying_parameter].keys():
                varying_xlabels[varying_parameter][item] = '$' + str(item) +'$'

    xlabels = [ varying_xlabels[varying_parameter][item] for item in ticks]

    if pltkind[(metric,varying_parameter)] is 'bar':
        p.set_xticks(sp.arange(len(ticks))+0.5)
        plt.setp(p.set_xticklabels(xlabels), rotation=0)
    else:
        plt.xticks(ticks,xlabels)

    plt.ylabel(ylabel_names[metric])
    plt.grid('on')
コード例 #20
0
def plot_subplots(offsets, tag, n, window):
  fig, axarr = plt.subplots(4, sharex=True, **dict(figsize=(12,12)))
  sel1 = np.logical_and(offsets['mchirp'] > 0.0, offsets['mchirp'] <= 5.0)
  sel2 = np.logical_and(offsets['mchirp'] > 5.0, offsets['mchirp'] <= 10.0)
  sel3 = np.logical_and(offsets['mchirp'] > 10.0, offsets['mchirp'] <= 15.0)
  sel4 = np.logical_and(offsets['mchirp'] > 15.0, offsets['mchirp'] <= 100.0)
  
  sel = [sel1, sel2, sel3, sel4]
  labels = [r'$\mathcal{M}\ \leq\ 5M_{\odot}$', r'$5M_{\odot}\ <\ \mathcal{M}\ \leq\ 10M_{\odot}$'\
      ,r'$10M_{\odot}\ <\ \mathcal{M}\ \leq\ 15M_{\odot}$', r'$\mathcal{M}\ >\ 15M_{\odot}$']
  
  hist_min = np.min(offsets['offset'][sel[0]])
  hist_max = np.max(offsets['offset'][sel[0]])
  
  for i in xrange(len(axarr)):
    if not np.any(sel[i]):
      continue
    axarr[i].hist(offsets['offset'][sel[i]], histtype='step', bins=n,\
        range=[hist_min, hist_max], label=labels[i])
    axarr[i].set_yscale('log', nonposy='clip')
    axarr[i].set_xlim(-window/2, window/2)
    axarr[i].set_ylabel(r'N')
    axarr[i].grid(True)
    axarr[i].legend(loc="upper left", bbox_to_anchor=(1,1))

  axarr[3].set_xlabel(r'Offset  [Sec]')
  fig.subplots_adjust(hspace=0.5)
  plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)

  axarr[0].set_title( tag)
  plt.savefig(tag + '_subplotshistogram.png', bbox_inches='tight')
  #, bbox_extra_artists=(lgd,), bbox_inches='tight')
  plt.close()
コード例 #21
0
def doplot():
    fig = plt.figure()
    gs = gridspec.GridSpec(4, 2)
    
    fig.suptitle('Tower motion for point load at top')

    ax = fig.add_subplot(gs[0,0])
    ax.plot(thrust_time, thrust[0]/1000, 'b')
    ax.set_ylabel('Thrust (kN)')
    
    ax = fig.add_subplot(gs[1:3,0])
    ax.plot(t, -100*y[1][:,2], 'b', label='Mine')
    ax.plot(t,  100*bladed_defl[:,0], 'k--', label='Bladed')
    ax.set_ylabel('x defl (cm)')
    ax.legend(frameon=False)
    #ax.set_ylim((0,0.045))
    plt.setp(ax.get_legend().get_texts(), fontsize='small')

    ax = fig.add_subplot(gs[1:3,1])
    ax.plot(t, y[2][:,1], 'b', label='Mine (midspan)')
    ax.plot(t, bladed_defl[:,1], 'k--', label='Bladed')
    ax.set_ylabel('y rot (rad)')
    
    ax = fig.add_subplot(gs[3,0])
    ax.plot(t, y[0][:,1])
    ax.set_ylabel('Transverse mode')
    
    ax = fig.add_subplot(gs[3,1])
    ax.plot(t, y[0][:,[4,6]])
    ax.set_ylabel('Rotation & normal modes')
コード例 #22
0
    def move_upperSlider(self):
        """ Re-setup upper range line in figure.
        Triggered by a change in Qt Widget.  NO EVENT is required.
        """
        inewy = self.ui.verticalSlider.value()

        # Return w/o change
        if inewy == self._upperSlideValue:
            return

        # Set to boundary value
        if inewy <= self._lowerSlideValue:
            inewy = self._lowerSlideValue + 1

        # Reset line editor?
        if inewy == 100 and self._upperSlideValue > 100:
            setLineEdit = False
        else:
            setLineEdit = True

        # Move the upper value bar: upperx and uppery are real value (float but not (0,100)) of the figure
        ylim = self.ui.mainplot.get_ylim()
        newy = ylim[0] + inewy*(ylim[1] - ylim[0])*0.01
        upperx = self.ui.mainplot.get_xlim()
        uppery = [newy, newy]
        setp(self.upperslideline, xdata=upperx, ydata=uppery)

        self.ui.graphicsView.draw()

            # Change value
        if setLineEdit is True:
            self.ui.lineEdit_6.setText(str(newy))
            self._upperSlideValue = inewy

        return
コード例 #23
0
ファイル: mds.py プロジェクト: dani-lbnl/lmt
def do_plot(mds, plot, ymax, extra=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    steps = mds.Steps.Steps
    values = mds.MDS.Values
    if ymax is None:
        ymax = np.max(values)
    Graph.timeSeries(ax, steps, values, 'b', label='MDS', Ave=True)
    plt.xlabel('time')
    plt.ylabel(r'$ops/sec$')
    if not mds.CPU is None:
        values = mds.CPU.Values
        (handles, labels) = Graph.percent(ax, steps, values, 'k',
                                          label='% CPU', Ave=True)
        if (not handles is None) and (not labels is None):
            plt.legend(handles, labels)
        else:
            print "mds.do_plot(): Warning - Plotting CPU utilization failed."
    else:
        plt.legend()
    plt.setp( ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    start_time = steps[0]/(24.0*60.0*60.0) + mpl.dates.date2num(datetime.date(1970,1,1))
    plt.title("%s metadata operations for %s" %
              (mds.name,
               mpl.dates.num2date(start_time).strftime("%Y-%m-%d"))
              )
    if ymax is None:
        ymax = ymax
    ax.set_ybound(lower=0, upper=ymax)
    if plot is None:
        plt.show()
    else:
        plt.savefig(plot)
    plt.cla()
コード例 #24
0
ファイル: PlotBar.py プロジェクト: ratulray/IsraelPalestine
def plot_bar(xlabels, Y):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    ## the data
    N = len(Y)
    ## necessary variables
    ind = np.arange(N)                # the x locations for the groups
    width = 0.35                      # the width of the bars
    
    ## the bars
    rects1 = ax.bar(ind, Y, width,
                    color='red')
    
    ax.set_xlim(-width,len(ind)+width)
    ax.set_ylim(0, max(Y)*1.2)
    ax.set_ylabel('Counts')
    ax.set_title('Counts by country')
    #xTickMarks = ['Group'+str(i) for i in range(1,6)]
    ax.set_xticks(ind+width)
    xtickNames = ax.set_xticklabels(xlabels)
    plt.setp(xtickNames, rotation=40, fontsize=10, ha='right')
    
    ## add a legend
    #ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )
    plt.tight_layout()
    plt.show()
コード例 #25
0
ファイル: analyze.py プロジェクト: amitsingh2783/kaggle
def plot_tfidf_classfeats(dfs):
    fig = plt.figure(figsize=(12, 9), facecolor="w")
    for i, df in enumerate(dfs):

        ax = fig.add_subplot(len(dfs), 1, i+1)
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        ax.set_frame_on(False)
        ax.get_xaxis().tick_bottom()
        ax.get_yaxis().tick_left()
        if i == len(dfs)-1:
            ax.set_xlabel("Feature name", labelpad=14, fontsize=14)
        ax.set_ylabel("Tf-Idf score", labelpad=16, fontsize=14)
        #if i == 0:
        ax.set_title("Mean Tf-Idf scores for label = " + str(df.label), fontsize=16)

        x = range(1, len(df)+1)
        ax.bar(x, df.tfidf, align='center', color='#3F5D7D')
        #ax.lines[0].set_visible(False)
        ax.set_xticks(x)
        ax.set_xlim([0,len(df)+1])
        xticks = ax.set_xticklabels(df.feature)
        #plt.ylim(0, len(df)+2)
        plt.setp(xticks, rotation='vertical') #, ha='right', va='top')
        plt.subplots_adjust(bottom=0.24, right=1, top=0.97, hspace=0.9)

    plt.show()
コード例 #26
0
ファイル: svnplotmatplotlib.py プロジェクト: YESLTD/svnplot
 def _drawScatterPlot(self,dates, values, plotidx, plotcount, title, refaxs):
     if( refaxs == None):
         logging.debug("initializing scatter plot")
         fig = plt.figure()
         #1 inch height for each author graph. So recalculate with height. Else y-scale get mixed.
         figHt = float(self.commitGraphHtPerAuthor*plotcount)
         fig.set_figheight(figHt)
         #since figureheight is in inches, set around maximum of 0.75 inches margin on top.
         topmarginfrac = min(0.15, 0.85/figHt)
         logging.debug("top/bottom margin fraction is %f" % topmarginfrac)
         fig.subplots_adjust(bottom=topmarginfrac, top=1.0-topmarginfrac, left=0.05, right=0.95)
     else:
         fig = refaxs.figure
         
     axs = fig.add_subplot(plotcount, 1, plotidx,sharex=refaxs,sharey=refaxs)
     axs.grid(True)
     axs.plot_date(dates, values, marker='.', xdate=True, ydate=False)
     axs.autoscale_view()
     
     #Pass None as 'handles' since I want to display just the titles
     axs.set_title(title, fontsize='small',fontstyle='italic')
     
     self._setXAxisDateFormatter(axs)        
     plt.setp( axs.get_xmajorticklabels(), visible=False)
     plt.setp( axs.get_xminorticklabels(), visible=False)
                 
     return(axs)
コード例 #27
0
ファイル: rooted_trees.py プロジェクト: alexfikl/nodepy
def plot_all_trees(p,title='str'):
#=====================================================
    """ Plots all rooted trees of order p.

        **Example**:

        Plot all trees of order 4::

            >>> from nodepy import rt
            >>> rt.plot_all_trees(4)  # doctest: +ELLIPSIS
            <matplotlib.figure.Figure object at ...>
    """
    import matplotlib.pyplot as pl
    forest=list_trees(p)
    nplots=len(forest)
    nrows=int(np.ceil(np.sqrt(float(nplots))))
    ncols=int(np.floor(np.sqrt(float(nplots))))
    if nrows*ncols<nplots: ncols=ncols+1
    for tree in forest:
        if title=='str': ttitle=tree
        else: ttitle=''
        tree.plot(nrows,ncols,forest.index(tree)+1,ttitle=ttitle)
    fig=pl.figure(1)
    pl.setp(fig,facecolor='white')
    return fig
コード例 #28
0
    def move_rightSlider(self):
        """ Re-setup left range line in figure.
        Triggered by a change in Qt Widget.  NO EVENT is required.
        """
        newx = self.ui.horizontalSlider_2.value()
        if newx >= self._leftSlideValue and newx != self._rightSlideValue:
            # Allowed value: move the value bar
            self._rightSlideValue = newx

            xlim = self.ui.mainplot.get_xlim()
            newx = xlim[0] + newx*(xlim[1] - xlim[0])*0.01
            leftx = [newx, newx]
            lefty = self.ui.mainplot.get_ylim()
            setp(self.rightslideline, xdata=leftx, ydata=lefty)

            self.ui.graphicsView.draw()

            # Change value
            self.ui.lineEdit_4.setText(str(newx))

        else:
            # Reset the value
            self.ui.horizontalSlider_2.setValue(self._rightSlideValue)

        return
コード例 #29
0
def plotSTAGE(show=False):
    fig, stage = plt.subplots(1)
    title="Stage for PT's in Nu'uuli Stream"
    #### PT1 stage N1
    stage.plot_date(PT1['stage'].index,PT1['stage'],marker='None',ls='-',color='r',label='N1')
    print 'Lowest PT1 stage: '+'%.1f'%PT1['stage'].min()
    #### PT2 stage N2
    stage.plot_date(PT2['stage'].index,PT2['stage'],marker='None',ls='-',color='y',label='N2')

    ## show storm intervals?
    showstormintervals(stage,shade_color='g',show=True)
    
    #### Format X axis and Primary Y axis
    stage.set_title(title)
    stage.set_ylabel('Stage height in cm')
    stage.set_ylim(0,145)
    stage.legend(loc=2)
    #### Add Precip data from Timu1
    AddTimu1(fig,stage,Precip['Timu-Nuuuli1-15'])
    AddTimu1(fig,stage,Precip['Timu-Nuuuli2-15'],LineColor='g')
    
    plt.setp(stage.get_xticklabels(),rotation='vertical',fontsize=9)
    plt.subplots_adjust(left=0.1,right=0.83,top=0.93,bottom=0.15)
    #### Legend
    plt.legend(loc=1)
    fig.canvas.manager.set_window_title('Figure 1: '+title) 
    stage.grid(True)
    show_plot(show)
    return
コード例 #30
0
def plot( name, data ) :
    
    dates = data["date"]
    times = data["time"]

    ddiff = max(dates)-min(dates)
    
    plt.close()
    plt.figure()    
    
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b-%d %X'))
    
    # set x-axis scale
    if ddiff.days > 60 :
        plt.gca().xaxis.set_major_locator(mdates.MonthLocator())
    elif ddiff.days > 2 :
        plt.gca().xaxis.set_major_locator(mdates.DayLocator())
    else :
        plt.gca().xaxis.set_major_locator(mdates.HourLocator())

    plt.plot( dates, times, 'bo-' )
    plt.gcf().autofmt_xdate()    

    plt.title( name )
    plt.xlabel( "Date" )
    plt.ylabel( "Time (s)" )
    plt.grid(True)
    plt.setp(plt.gca().get_xmajorticklabels(), size=6,rotation=30) 
#    plt.show()
    plt.savefig( name )
コード例 #31
0
def create_eval_plot(df_dice, df_haus=None, df_hd=None, df_vol=None, eval=None):
    """
    Create a violinplot with an integrated bland altmann plot
    Nobs = median
    Expects the following dataframe structure (created in notebooks/Evaluate/Evaluate_create_plots.ipynb):
        Name 	Dice LV 	Volume LV 	Err LV(ml) 	Hausdorff LV 	Dice RV 	Volume RV 	Err RV(ml) 	Hausdorff RV 	Dice MYO 	Volume MYO 	Err MYO(ml) 	Hausdorff MYO
    0 	0000-0HQQW4ZN_2007-05-23_ED_msk 	0.897436 	110.887500 	-7.106250 	5.744563 	0.868490 	149.231250 	-30.600000 	7.211103 	0.619342 	57.768750 	-2.925000 	10.000000
    1 	0000-0HQQW4ZN_2007-05-23_ES_msk 	0.850738 	43.443750 	4.921875 	4.123106 	0.830049 	82.743750 	-3.862500 	10.816654 	0.695500 	51.993750 	2.325000 	5.830952
    Parameters
    ----------
    df_dice : pd.dataframe - melted dice dataframe
    df_haus : pd.dataframe - melted dataframe with the hausdorff
    df_hd : pd.dataframe - melted dataframe with the difference (pred-gt) of the volumes
    df_vol : pd.dataframe - melted dataframe with the predicted volume
    eval : pd.dataframe - full dataframe as shown in the fn description

    Returns
    -------

    """

    import seaborn as sns
    outliers = False
    # make sure the color schema reflects the RGB schema of show_slice_transparent
    my_pal_1 = {"Dice LV": "dodgerblue", "Dice MYO": "g", "Dice RV": "darkorange"}
    my_pal_2 = {"Err LV(ml)": "dodgerblue", "Err MYO(ml)": "g", "Err RV(ml)": "darkorange"}
    my_pal_3 = {"Volume LV": "dodgerblue", "Volume MYO": "g", "Volume RV": "darkorange"}
    hd_pal = {"Hausdorff LV": "dodgerblue", "Hausdorff MYO": "g", "Hausdorff RV": "darkorange"}

    plt.rcParams.update({'font.size': 20})
    if df_haus is not None:
        fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(25, 8), sharey=False)
    else:
        fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(25, 8), sharey=False)

    ax1 = sns.violinplot(x='variable', y='value', data=df_dice, order=["Dice LV", "Dice MYO", "Dice RV"],
                         palette=my_pal_1, showfliers=outliers, ax=ax1)
    mean = df_dice.groupby(['variable'])['value'].mean().round(2)
    sd = df_dice.groupby(['variable'])['value'].std().round(2)
    nobs = ['{}+/-{}'.format(m, s) for m, s in zip(mean, sd)]

    for tick, label in zip(range(len(ax1.get_xticklabels())), ax1.get_xticklabels()):
        _ = ax1.text(tick, mean[tick], nobs[tick], horizontalalignment='center', size='x-small', color='black',
                     weight='semibold')
    plt.setp(ax1, ylim=(0, 1))
    plt.setp(ax1, ylabel=('DICE'))
    plt.setp(ax1, xlabel='')
    ax1.set_xticklabels(['LV', 'MYO', 'RV'])

    # create bland altmannplot from vol diff
    ax2 = bland_altman_metric_plot(eval, ax2)

    # create violin plot for the volume
    ax3 = sns.violinplot(x='variable', y='value', order=["Volume LV", "Volume MYO", "Volume RV"], palette=my_pal_3,
                         showfliers=outliers, data=df_vol, ax=ax3)

    mean = df_vol.groupby(['variable'])['value'].mean().round(2)
    sd = df_vol.groupby(['variable'])['value'].std().round(2)
    nobs = ['{}+/-{}'.format(m, s) for m, s in zip(mean, sd)]

    for tick, label in zip(range(len(ax3.get_xticklabels())), ax3.get_xticklabels()):
        _ = ax3.text(tick, mean[tick], nobs[tick], horizontalalignment='center', size='x-small', color='black',
                     weight='semibold')
    # plt.setp(ax3, ylim=(0,500))
    plt.setp(ax3, ylabel=('Vol size in ml'))
    plt.setp(ax3, xlabel='')
    ax3.set_xticklabels(['LV', 'MYO', 'RV'])

    ax4 = sns.violinplot(x='variable', y='value', order=["Hausdorff LV", "Hausdorff MYO", "Hausdorff RV"],
                         palette=hd_pal,
                         showfliers=outliers, data=df_haus, ax=ax4)

    mean = df_haus.groupby(['variable'])['value'].mean().round(2)
    sd = df_haus.groupby(['variable'])['value'].std().round(2)
    nobs = ['{}+/-{}'.format(m, s) for m, s in zip(mean, sd)]

    for tick, label in zip(range(len(ax4.get_xticklabels())), ax4.get_xticklabels()):
        _ = ax4.text(tick, mean[tick], nobs[tick], horizontalalignment='center', size='x-small', color='black',
                     weight='semibold')
    plt.setp(ax4, ylim=(0, 50))
    plt.setp(ax4, ylabel=('Hausdorff distance'))
    plt.setp(ax4, xlabel='')
    ax4.set_xticklabels(['LV', 'MYO', 'RV'])
    plt.tight_layout()
    return fig
コード例 #32
0
ファイル: identifyGUI_panels.py プロジェクト: cclemente/ppp2
 def _create_axes(self):
     self.ax = self.figure.add_axes((0, 0, 1, 1), axisbg=[0.5] * 3)
     # self.plot(None)
     # self.ax.plot( np.random.randn(10) )
     pyplot.setp(self.ax, xticks=[], yticks=[])
コード例 #33
0
ファイル: visualisations.py プロジェクト: zionnub/MYProjs
plot = df1.max().plot.pie(y=df1.max().index, figsize=(5, 5),autopct=absolute_value, label='')
plot.set_title('Total Number of Deaths', fontsize=12)
pyplot.show()

#Credit https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/image_annotated_heatmap.html
import numpy as np
from matplotlib import pyplot
df1 = df1.tail(15)
dates = df1.index.strftime('%Y-%b-%d')
countries = df1.max().index
df2 = pd.DataFrame(df1, columns=df1.columns).astype(int)
matrix = np.array(df2).transpose()
fig, ax = pyplot.subplots()
im = ax.imshow(matrix)
# We want to show all ticks...
ax.set_xticks(np.arange(len(dates)))
ax.set_yticks(np.arange(len(countries)))
# ... and label them with the respective list entries
ax.set_xticklabels(dates)
ax.set_yticklabels(countries)
# Rotate the tick labels and set their alignment.
pyplot.setp(ax.get_xticklabels(), rotation=45, ha="right",
         rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(dates)):
    for j in range(len(countries)):
        text = ax.text(i, j, matrix[j, i],
                       ha="center", va="center", color="w", size = '6')
ax.set_title("Deaths Per Day Heatmap")
fig.tight_layout()
pyplot.show()
コード例 #34
0
ファイル: main.py プロジェクト: Doctor-Wh0/voice_reco
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=CHUNK)

x = np.arange(0, 2 * CHUNK, 2)

line, = ax.plot(x, np.random.rand(CHUNK), '-', lw=2)

ax.set_title('AUDIO WAVEFORM')
ax.set_xlabel('samples')
ax.set_ylabel('volume')
ax.set_ylim(0, 255)
ax.set_xlim(0, 2 * CHUNK)
plt.setp(ax, xticks=[0, CHUNK, 2 * CHUNK], yticks=[0, 128, 255])

plt.show(block=False)

print('stream started')

#for measuring framerate

frame_count = 0
start_time = time.time()

while True:
    # bin data
    data = stream.read(CHUNK)

    #convert data to integers, make np array, then offset it by 127
コード例 #35
0
def main(algo, nb_games, txt_to_read, n_test, Verbose=False, sup=18, new_winning_dataset = False, txt = 'test.csv'): #new_winning_dataset = True if the dataset has not been generated yet
                                                                                                                          #txt to name the output csv, txt_to_read to get the name of the csv to get
    win = 0
    tie = 0
    loss = 0
    nb_games_played = 0

    # initialization of the game
    df = pd.DataFrame(columns = ['player_hand_value','dealer_first_card', 'usable_ace', 'deck_value' , 'action',1,2,3,4,5,6,7,8,9,10])

    # while loop to run enough games to store nb_games
    if new_winning_dataset :
        while (nb_games_played < nb_games) :
            player_hand, dealer_first_card, usable_ace = env.new_game()

            # in the official rules, there can only be a maximum of 2 passes, but we will not implement this rule
            # (not relevant)
            # theoretically ,there cannot be more than 11 passes (4*aces, 4*two, 3*three)
            for t in range(11):
                act = action(algo, player_hand, sup, dealer_first_card, usable_ace, t)
                # If the player has a blackjack, he automatically stands
                if sum(player_hand) == 21 :
                    act = 0

                # features enabling to count the cards
                deck_value = env.get_deck_value()
                deck_counting_cards = env.get_deck_cards_counting()

                if (t == 0) :
                    state = [bj.sum_hand(player_hand), dealer_first_card, bj.has_ace(player_hand)*1, deck_value,act] + list(deck_counting_cards)
                    opposite_state = [bj.sum_hand(player_hand), dealer_first_card, bj.has_ace(player_hand)*1, deck_value, 1 - act] + list(deck_counting_cards)

                observation, reward, done, info = env.step(act)
                player_hand, dealer_first_card, usable_ace = observation

                if done:
                    # if the player won the game, we store the game
                    if reward >= 0:
                        df.loc[nb_games_won] = state
                    else :
                        df.loc[nb_games_won] = opposite_state
                    nb_games_played += 1
                    if (nb_games_played % (nb_games//10) == 0) :
                        print('|', end='')
                    break

        env.close()
        df.to_csv(txt,index = False)

    else :
        df = pd.read_csv(txt_to_read)

    # Train the model with the dataset
    model = Sequential()
    model.add(Dense(16, kernel_initializer='lecun_uniform'))
    model.add(Activation('relu'))

    model.add(Dense(256, kernel_initializer='lecun_uniform'))
    model.add(Activation('relu'))

    model.add(Dense(128, kernel_initializer='lecun_uniform'))
    model.add(Activation('relu'))

    model.add(Dense(32, kernel_initializer='lecun_uniform'))
    model.add(Activation('relu'))

    model.add(Dense(8, kernel_initializer='lecun_uniform'))
    model.add(Activation('relu'))
        
    model.add(Dense(1, kernel_initializer='lecun_uniform'))
    model.add(Activation('sigmoid'))

    model.compile(loss='mse', optimizer='adam')

    X_train = np.array(df[['dealer_first_card','player_hand_value', 'usable_ace','deck_value']])
    y_train = np.array(df['action']).reshape(-1,1)
    model.fit( X_train, y_train, epochs=20)

    #ROC CURVE : play 10000 games and test predict them
    actuals = []
    pred_Y_train = []

    for i in range(10000) :
            player_hand, dealer_first_card, usable_ace = env.new_game()
            for t in range(11):
                act = action(algo, player_hand, sup, dealer_first_card, usable_ace, t)
                if sum(player_hand) == 21 :
                    act = 0
                deck_value = env.get_deck_value()
                deck_counting_cards = env.get_deck_cards_counting()

                if (t == 0) :
                    state = [bj.sum_hand(player_hand), dealer_first_card, bj.has_ace(player_hand)*1, deck_value, act] 
                    opposite_state = [bj.sum_hand(player_hand), dealer_first_card, bj.has_ace(player_hand)*1, deck_value, 1 - act] 

                    cur_state = [[bj.sum_hand(player_hand), dealer_first_card, bj.has_ace(player_hand)*1, deck_value]]
                    p = model.predict(np.array(cur_state)[0:1], batch_size=1)            
                    pred_Y_train.append(p[0][0])

                observation, reward, done, info = env.step(act)
                player_hand, dealer_first_card, usable_ace = observation

                if done:
                    if reward >= 0:
                        actuals.append(state[4])
                    else :
                        actuals.append(opposite_state[4])
                    break

    env.close()
    
    fpr, tpr, threshold = metrics.roc_curve(actuals, pred_Y_train)
    roc_auc = metrics.auc(fpr, tpr)

    fig, ax = plt.subplots(figsize=(10,8))
    plt.plot(fpr, tpr, label = ('ROC AUC = %0.3f' % roc_auc))

    plt.legend(loc = 'lower right')
    plt.plot([0, 1], [0, 1],'r--')
    plt.xlim([0, 1])
    plt.ylim([0, 1])
    ax.set_xlabel("False Positive Rate",fontsize=12)
    ax.set_ylabel("True Positive Rate",fontsize=12)
    plt.setp(ax.get_legend().get_texts(), fontsize=12)
    plt.show()



    # Use the model to predict
    for i_game in range(n_test):

        player_hand, dealer_first_card, usable_ace = env.new_game()

        # in the official rules, there can only be a maximum of 2 passes, but we will not implement this rule
        # (not relevant)
        # theoretically ,there cannot be more than 11 passes (4*aces, 4*two, 3*three)
        for t in range(11):
            # Counting the cards
            deck_value = env.get_deck_value()
            deck_counting_cards = env.get_deck_cards_counting()

            # Choosing the next action
            state = [[bj.sum_hand(player_hand),dealer_first_card, bj.has_ace(player_hand)*1,deck_value]] 
            act = 0
            p = model.predict(np.array(state)[0:1], batch_size=1)
            if ( (p > 0.5)) :
                act = 1
            
            # Playing
            observation, reward, done, info = env.step(act)
            player_hand, dealer_first_card, usable_ace = observation

            if done:
                if reward >= 1:
                    win += 1

                elif reward == 0:
                    tie += 1

                elif reward == -1:
                    loss += 1

                break

    # percentage of winning games
    return 100 * win / n_test, 100 * tie / n_test, 100 * loss/n_test
コード例 #36
0
def vis_one_image(
        im, im_name, output_dir, boxes, segms=None, keypoints=None, thresh=0.9,
        kp_thresh=2, dpi=200, box_alpha=0.0, dataset=None, show_class=False,
        ext='pdf'):
    """Visual debugging of detections."""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    if isinstance(boxes, list):
        boxes, segms, keypoints, classes = convert_from_cls_format(
            boxes, segms, keypoints)

    if boxes is None or boxes.shape[0] == 0 or max(boxes[:, 4]) < thresh:
        return

    dataset_keypoints, _ = keypoint_utils.get_keypoints()

    if segms is not None and len(segms) > 0:
        masks = mask_util.decode(segms)

    color_list = colormap(rgb=True) / 255

    kp_lines = kp_connections(dataset_keypoints)
    cmap = plt.get_cmap('rainbow')
    colors = [cmap(i) for i in np.linspace(0, 1, len(kp_lines) + 2)]

    fig = plt.figure(frameon=False)
    fig.set_size_inches(im.shape[1] / dpi, im.shape[0] / dpi)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.axis('off')
    fig.add_axes(ax)
    ax.imshow(im)

    # Display in largest to smallest order to reduce occlusion
    areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
    sorted_inds = np.argsort(-areas)

    mask_color_id = 0
    for i in sorted_inds:
        bbox = boxes[i, :4]
        score = boxes[i, -1]
        if score < thresh:
            continue

        # show box (off by default)
        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1],
                          fill=False, edgecolor='g',
                          linewidth=0.5, alpha=box_alpha))

        if show_class:
            ax.text(
                bbox[0], bbox[1] - 2,
                get_class_string(classes[i], score, dataset),
                fontsize=3,
                family='serif',
                bbox=dict(
                    facecolor='g', alpha=0.4, pad=0, edgecolor='none'),
                color='white')

        # show mask
        if segms is not None and len(segms) > i:
            img = np.ones(im.shape)
            color_mask = color_list[mask_color_id % len(color_list), 0:3]
            mask_color_id += 1

            w_ratio = .4
            for c in range(3):
                color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio
            for c in range(3):
                img[:, :, c] = color_mask[c]
            e = masks[:, :, i]

            _, contour, hier = cv2.findContours(
                e.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)

            for c in contour:
                polygon = Polygon(
                    c.reshape((-1, 2)),
                    fill=True, facecolor=color_mask,
                    edgecolor='w', linewidth=1.2,
                    alpha=0.5)
                ax.add_patch(polygon)

        # show keypoints
        if keypoints is not None and len(keypoints) > i:
            kps = keypoints[i]
            plt.autoscale(False)
            for l in range(len(kp_lines)):
                i1 = kp_lines[l][0]
                i2 = kp_lines[l][1]
                if kps[2, i1] > kp_thresh and kps[2, i2] > kp_thresh:
                    x = [kps[0, i1], kps[0, i2]]
                    y = [kps[1, i1], kps[1, i2]]
                    line = plt.plot(x, y)
                    plt.setp(line, color=colors[l], linewidth=1.0, alpha=0.7)
                if kps[2, i1] > kp_thresh:
                    plt.plot(
                        kps[0, i1], kps[1, i1], '.', color=colors[l],
                        markersize=3.0, alpha=0.7)

                if kps[2, i2] > kp_thresh:
                    plt.plot(
                        kps[0, i2], kps[1, i2], '.', color=colors[l],
                        markersize=3.0, alpha=0.7)

            # add mid shoulder / mid hip for better visualization
            mid_shoulder = (
                kps[:2, dataset_keypoints.index('right_shoulder')] +
                kps[:2, dataset_keypoints.index('left_shoulder')]) / 2.0
            sc_mid_shoulder = np.minimum(
                kps[2, dataset_keypoints.index('right_shoulder')],
                kps[2, dataset_keypoints.index('left_shoulder')])
            mid_hip = (
                kps[:2, dataset_keypoints.index('right_hip')] +
                kps[:2, dataset_keypoints.index('left_hip')]) / 2.0
            sc_mid_hip = np.minimum(
                kps[2, dataset_keypoints.index('right_hip')],
                kps[2, dataset_keypoints.index('left_hip')])
            if (sc_mid_shoulder > kp_thresh and
                    kps[2, dataset_keypoints.index('nose')] > kp_thresh):
                x = [mid_shoulder[0], kps[0, dataset_keypoints.index('nose')]]
                y = [mid_shoulder[1], kps[1, dataset_keypoints.index('nose')]]
                line = plt.plot(x, y)
                plt.setp(
                    line, color=colors[len(kp_lines)], linewidth=1.0, alpha=0.7)
            if sc_mid_shoulder > kp_thresh and sc_mid_hip > kp_thresh:
                x = [mid_shoulder[0], mid_hip[0]]
                y = [mid_shoulder[1], mid_hip[1]]
                line = plt.plot(x, y)
                plt.setp(
                    line, color=colors[len(kp_lines) + 1], linewidth=1.0,
                    alpha=0.7)

    output_name = os.path.basename(im_name) + '.' + ext
    fig.savefig(os.path.join(output_dir, '{}'.format(output_name)), dpi=dpi)
    plt.close('all')
コード例 #37
0
def  environmentalgraph2(source,days,delay):


	
	print("environmentalgraph2 source:%s days:%s" % (source,days))
	print("sleeping seconds:", delay)
	time.sleep(delay)
	print("envrironmentalgraph2 running now")
	

	# blink GPIO LED when it's run
	GPIO.setmode(GPIO.BOARD)
        GPIO.setup(22, GPIO.OUT)
        GPIO.output(22, False)
        time.sleep(0.5)
        GPIO.output(22, True)

	# now we have get the data, stuff it in the graph 

	try:
		print("trying database")
    		db = mdb.connect('localhost', 'root', conf.databasePassword, 'ProjectCuracao');

    		cursor = db.cursor()

		query = "SELECT TimeStamp, BarometricPressure, Luminosity, FanState FROM environmentaldata where  now() - interval %i hour < TimeStamp" % (days*24)
		#query = "SELECT TimeStamp, InsideTemperature, InsideHumidity, OutsideTemperature, BarometricPressure, Luminosity, FanState  FROM environmentaldata where  now() - interval %i hour < TimeStamp" % (days*24)
		cursor.execute(query)
		result = cursor.fetchall()

		t = []
		s = []
		u = []
		v = []

		for record in result:
  			t.append(record[0])
  			s.append(record[1])
  			u.append(record[2])
  			v.append(record[3])

		#dts = map(datetime.datetime.fromtimestamp, s)
		#fds = dates.date2num(t) # converted
		# matplotlib date format object
		hfmt = dates.DateFormatter('%m/%d-%H')

		fig = pyplot.figure()
		
		ax = fig.add_subplot(111)
		
                #ax.vlines(fds, -200.0, 1000.0,colors='w')
                ax.xaxis.set_major_locator(dates.HourLocator(interval=6))
		ax.xaxis.set_major_formatter(hfmt)
		pylab.xticks(rotation='vertical')

		pyplot.subplots_adjust(bottom=.3)
		pylab.plot(t, s, color='b',label="Barometric Pressure (mb) ",linestyle="-",marker=".")
		pylab.xlabel("Hours")
		pylab.ylabel("millibars")
		pylab.legend(loc='upper left')
		pylab.axis([min(t), max(t), 900, 1100])
		ax2 = pylab.twinx()
		pylab.ylabel("lux and  fan(0/1) ")

		# scale array

		for i in range(len(v)):
			v[i] = v[i] * 500
		

		pylab.plot(t, u, color='y',label="Luminosity (lux)",linestyle="-",marker=".")
		pylab.plot(t, v, color='r',label="Fan State (0/1)",linestyle="-",marker=".")
		pylab.axis([min(t), max(t), 0, max(u)])
		pylab.legend(loc='lower left')
		pylab.figtext(.5, .05, ("Environmental Statistics Last %i Days" % days),fontsize=18,ha='center')

		#pylab.grid(True)

		pyplot.setp( ax.xaxis.get_majorticklabels(), rotation=70)
		ax.xaxis.set_major_formatter(dates.DateFormatter('%m/%d-%H'))
		pyplot.show()
		pyplot.savefig("/home/pi/RasPiConnectServer/static/environmentalgraph2.png")	
		
	except mdb.Error, e:
  
    		print "Error %d: %s" % (e.args[0],e.args[1])
コード例 #38
0
ファイル: matrix.py プロジェクト: pyeguy/seaborn
    def plot_colors(self, xind, yind, **kws):
        """Plots color labels between the dendrogram and the heatmap

        Parameters
        ----------
        heatmap_kws : dict
            Keyword arguments heatmap
        """
        # Remove any custom colormap and centering
        kws = kws.copy()
        kws.pop('cmap', None)
        kws.pop('center', None)
        kws.pop('vmin', None)
        kws.pop('vmax', None)
        kws.pop('robust', None)
        kws.pop('xticklabels', None)
        kws.pop('yticklabels', None)

        # Plot the row colors
        if self.row_colors is not None:
            matrix, cmap = self.color_list_to_matrix_and_cmap(self.row_colors,
                                                              yind,
                                                              axis=0)

            # Get row_color labels
            if self.row_color_labels is not None:
                row_color_labels = self.row_color_labels
            else:
                row_color_labels = False

            heatmap(matrix,
                    cmap=cmap,
                    cbar=False,
                    ax=self.ax_row_colors,
                    xticklabels=row_color_labels,
                    yticklabels=False,
                    **kws)

            # Adjust rotation of labels
            if row_color_labels is not False:
                plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90)
        else:
            despine(self.ax_row_colors, left=True, bottom=True)

        # Plot the column colors
        if self.col_colors is not None:
            matrix, cmap = self.color_list_to_matrix_and_cmap(self.col_colors,
                                                              xind,
                                                              axis=1)

            # Get col_color labels
            if self.col_color_labels is not None:
                col_color_labels = self.col_color_labels
            else:
                col_color_labels = False

            heatmap(matrix,
                    cmap=cmap,
                    cbar=False,
                    ax=self.ax_col_colors,
                    xticklabels=False,
                    yticklabels=col_color_labels,
                    **kws)

            # Adjust rotation of labels, place on right side
            if col_color_labels is not False:
                self.ax_col_colors.yaxis.tick_right()
                plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0)
        else:
            despine(self.ax_col_colors, left=True, bottom=True)
コード例 #39
0
def periodAnalysisPlot(folder, name='PeriodicityAll5.npz'):
    npzfile = np.load(os.path.join(folder, name))
    period_array = npzfile['arr_0']
    QD_array = npzfile['arr_1']
    width_array = npzfile['arr_2']
    count_array = npzfile['arr_3']
    period_list = period_array.tolist()
    period_list = [0 if x is None else x for x in period_list]
    period_array = np.array(period_list)
    #print(period_array.tolist())
    #print(width_array[np.where(period_array==0)], QD_array[np.where(period_array==0)], count_array[np.where(period_array==0)])

    fig, ax = plt.subplots(1, 1)
    total = period_array.size
    bin_number = np.ceil(np.sqrt(total)) // 2 * 2 + 1
    bins = np.linspace(-.5, 15, num=17)
    print(period_array.tolist())
    ax.hist(period_array,
            log=True,
            normed=True,
            bins=bins,
            alpha=1,
            label='Period of Memory',
            rwidth=0.8)
    ax.set_xlabel('Period')
    ax.set_ylabel('Probability of occurring')

    fig, ax = plt.subplots(1, 1)
    total = period_array.size
    bin_number = np.ceil(np.sqrt(total)) // 2 * 2 + 1
    bins = np.linspace(-0.5, 15, num=7)
    print(period_array.tolist())
    ax.hist(period_array,
            log=True,
            bins=bins,
            alpha=1,
            label='Period of Memory',
            rwidth=0.8)
    ax.set_xlabel('Period')
    ax.set_ylabel('Number of occurrences')

    data_dict = {
        'version': count_array,
        'QD': QD_array * 100,
        'Width': width_array * 1e-9,
        'Count': period_array
    }

    data_df = pd.DataFrame(data_dict)
    grouped = data_df.groupby('version')

    data = data_df.groupby(by=['Width', 'QD']).mean()
    piv = pd.pivot_table(data,
                         values='Count',
                         index=['QD'],
                         columns=['Width'],
                         fill_value=0)

    plt.figure()
    yticks = piv.index.values.round(2).tolist()[::4]
    ax = sns.heatmap(piv,
                     vmin=0,
                     vmax=6,
                     square=True,
                     yticklabels=yticks[::1],
                     cbar_kws={'label': 'Average period of lattice'},
                     cmap='Blues',
                     xticklabels=4)
    ax.set_yticks(np.array(yticks) * ax.get_ylim()[1] / 10.)
    ax.invert_yaxis()
    plt.tight_layout()
    ax.set_ylabel('Quenched Disorder (%)')
    ax.set_xlabel('Width (nm)')
    plt.setp(ax.get_xticklabels(), rotation=90, horizontalalignment='right')
    plt.setp(ax.get_yticklabels(), rotation=0, verticalalignment='top')

    for vers, group in grouped:
        print(vers)
        data = group.groupby(by=['Width', 'QD']).mean()
        piv = pd.pivot_table(data,
                             values='Count',
                             index=['QD'],
                             columns=['Width'],
                             fill_value=0)
        plt.figure()
        print(piv.index.values.round(2))
        print(list(piv.index.values.round(2))[::4])
        print(piv.index.values.round(2).tolist()[::4])
        yticks = piv.index.values.round(2).tolist()[::4]
        ax = sns.heatmap(piv,
                         vmin=0,
                         vmax=6,
                         square=True,
                         yticklabels=yticks[::1],
                         cbar_kws={'label': 'Average period of lattice'},
                         cmap='Blues',
                         xticklabels=4)
        ax.set_yticks(np.array(yticks) * ax.get_ylim()[1] / 10.)
        ax.invert_yaxis()
        plt.tight_layout()
        ax.set_ylabel('Quenched Disorder (%)')
        ax.set_xlabel('Width (nm)')
        plt.setp(ax.get_xticklabels(),
                 rotation=90,
                 horizontalalignment='right')
        plt.setp(ax.get_yticklabels(), rotation=0, verticalalignment='top')
コード例 #40
0
def plot_confusion_matrix(y_true, y_pred, classes,
                          normalize=False,
                          title=None,
                          cmap=plt.cm.Blues):
    '''
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    Parameters
    ----------
    y_true :
    y_pred :
    classes :
    normalize :
    title :
    cmap :

    Returns
    -------

    '''
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'

    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    # Only use the labels that appear in the data
    # classes = classes[unique_labels(y_true, y_pred)]

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    logging.info(cm)

    fig, ax = plt.subplots(figsize=(15, 10))
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.figure.colorbar(im, ax=ax)
    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           # ... and label them with the respective list entries
           xticklabels=classes, yticklabels=classes,
           title=title,
           ylabel='True label',
           xlabel='Predicted label')

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    fmt = '.3f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    return ax
コード例 #41
0
                 fnl_hght,
                 colors='white',
                 linewidths=.5,
                 zorder=101,
                 transform=ccrs.PlateCarree())

label1 = ax.clabel(cs1,
                   fontsize=6,
                   colors='white',
                   inline=1,
                   inline_spacing=2,
                   fmt='%i',
                   rightside_up=True,
                   use_clabeltext=False)
plt.setp(
    label1,
    path_effects=[PathEffects.withStroke(linewidth=1.5, foreground="black")])

label2 = ax.clabel(cs2,
                   fontsize=6,
                   colors='white',
                   inline=1,
                   inline_spacing=2,
                   fmt='%i',
                   rightside_up=True,
                   use_clabeltext=False)

for l in label1 + label2:
    l.set_rotation(0)

b1 = ax.barbs(lon,
コード例 #42
0
        & (dataset["Parch"] == dataset.iloc[i]["Parch"])
        & (dataset["Pclass"] == dataset.iloc[i]["Pclass"]))].median()
    if not np.isnan(age_pred):
        dataset["Age"].iloc[i] = age_pred
    else:
        dataset["Age"].iloc[i] = age_med
g = sns.factorplot(x="Survived", y="Age", data=train, kind="box")
g = sns.factorplot(x="Survived", y="Age", data=train, kind="violin")
dataset["Name"].head()
dataset_title = [
    i.split(",")[1].split(".")[0].strip() for i in dataset["Name"]
]
dataset["Title"] = pd.Series(dataset_title)
dataset["Title"].head()
g = sns.countplot(x="Title", data=dataset)
g = plt.setp(g.get_xticklabels(), rotation=45)
dataset["Title"] = dataset["Title"].replace(
    [
        "Lady",
        "the Countess",
        "Countess",
        "Capt",
        "Col",
        "Don",
        "Dr",
        "Major",
        "Rev",
        "Sir",
        "Jonkheer",
        "Dona",
    ],
コード例 #43
0
ファイル: GrainTrain.py プロジェクト: BPInsects/BpInsect
    errors.append(model.loss_)Y_index = []
errors = []

for Y in range(3, 20):
    model = MLPClassifier(solver='sgd', alpha=1e-5, hidden_layer_sizes=(Y,), random_state=1, max_iter=100000,
                          momentum=0.9,
                          activation='relu', learning_rate_init=0.001)

    model.fit(x_train, y_train)
    Y_index.append(Y)
line = plt.plot(Y_index, errors)
plt.title('test layer size for error')
plt.xlabel('hidden_layers_sizes')
plt.ylabel('error')
plt.yscale('symlog', linthreshy=0.5)
plt.setp(line, 'color', 'r', 'linewidth', 2.0)
plt.show()

model = MLPClassifier(solver='sgd', alpha=1e-5, hidden_layer_sizes=(15,), random_state=1, max_iter=100000,
                      momentum=0.9,
                      verbose=10,
                      activation='relu', learning_rate_init=0.001, tol=1e-5)

model.fit(x_train, y_train)
print( model.n_layers_)
print( model.loss_)
print( model.out_activation_)
start = time.clock()
print(model.score(x_test, y_test))
print(x_test)
print(model.predict(x_test))
コード例 #44
0
def showdatas(dating_data_mat, dating_labels):
    """
    函数说明:可视化数据
    Parameters:
        dating_data_mat - 特征矩阵
        dating_labels - 分类Label
    Returns:
        无
    """
    #将fig画布分隔成1行1列,不共享x轴和y轴,fig画布的大小为(13,8)
    #当nrow=2,nclos=2时,代表fig画布被分为四个区域,axs[0][0]表示第一行第一个区域
    fig, axs = plt.subplots(nrows=2,
                            ncols=2,
                            sharex=False,
                            sharey=False,
                            figsize=(13, 8))
    number_of_lables = len(dating_labels)
    labels_colors = []
    for i in dating_labels:
        if i == 1:
            labels_colors.append('black')
        if i == 2:
            labels_colors.append('orange')
        if i == 3:
            labels_colors.append('red')

    #画出散点图,以dating_data_mat矩阵的第一(飞行常客例程)、第二列(玩游戏)数据画散点数据,散点大小为15,透明度为0.5
    axs[0][0].scatter(x=dating_data_mat[:, 0],
                      y=dating_data_mat[:, 1],
                      color=labels_colors,
                      s=15,
                      alpha=.5)
    #设置标题,x轴label,y轴label
    axs0_title_text = axs[0][0].set_title(u'每年获得的飞行常客里程数与玩视频游戏所消耗时间占比',
                                          FontProperties=font)
    axs0_xlabel_text = axs[0][0].set_xlabel(u'每年获得的飞行常客里程数',
                                            FontProperties=font)
    axs0_ylabel_text = axs[0][0].set_ylabel(u'玩视频游戏所消耗时间占比',
                                            FontProperties=font)
    plt.setp(axs0_title_text, size=9, weight='bold', color='red')
    plt.setp(axs0_xlabel_text, size=7, weight='bold', color='black')
    plt.setp(axs0_ylabel_text, size=7, weight='bold', color='black')

    #画出散点图,以dating_data_mat矩阵的第一(飞行常客例程)、第三列(冰激凌)数据画散点数据,散点大小为15,透明度为0.5
    axs[0][1].scatter(x=dating_data_mat[:, 0],
                      y=dating_data_mat[:, 2],
                      color=labels_colors,
                      s=15,
                      alpha=.5)
    #设置标题,x轴label,y轴label
    axs1_title_text = axs[0][1].set_title(u'每年获得的飞行常客里程数与每周消费的冰激淋公升数',
                                          FontProperties=font)
    axs1_xlabel_text = axs[0][1].set_xlabel(u'每年获得的飞行常客里程数',
                                            FontProperties=font)
    axs1_ylabel_text = axs[0][1].set_ylabel(u'每周消费的冰激淋公升数',
                                            FontProperties=font)
    plt.setp(axs1_title_text, size=9, weight='bold', color='red')
    plt.setp(axs1_xlabel_text, size=7, weight='bold', color='black')
    plt.setp(axs1_ylabel_text, size=7, weight='bold', color='black')

    #画出散点图,以dating_data_mat矩阵的第二(玩游戏)、第三列(冰激凌)数据画散点数据,散点大小为15,透明度为0.5
    axs[1][0].scatter(x=dating_data_mat[:, 1],
                      y=dating_data_mat[:, 2],
                      color=labels_colors,
                      s=15,
                      alpha=.5)
    #设置标题,x轴label,y轴label
    axs2_title_text = axs[1][0].set_title(u'玩视频游戏所消耗时间占比与每周消费的冰激淋公升数',
                                          FontProperties=font)
    axs2_xlabel_text = axs[1][0].set_xlabel(u'玩视频游戏所消耗时间占比',
                                            FontProperties=font)
    axs2_ylabel_text = axs[1][0].set_ylabel(u'每周消费的冰激淋公升数',
                                            FontProperties=font)
    plt.setp(axs2_title_text, size=9, weight='bold', color='red')
    plt.setp(axs2_xlabel_text, size=7, weight='bold', color='black')
    plt.setp(axs2_ylabel_text, size=7, weight='bold', color='black')
    #设置图例
    didntLike = mlines.Line2D([], [],
                              color='black',
                              marker='.',
                              markersize=6,
                              label='didntLike')
    smallDoses = mlines.Line2D([], [],
                               color='orange',
                               marker='.',
                               markersize=6,
                               label='smallDoses')
    largeDoses = mlines.Line2D([], [],
                               color='red',
                               marker='.',
                               markersize=6,
                               label='largeDoses')
    #添加图例
    axs[0][0].legend(handles=[didntLike, smallDoses, largeDoses])
    axs[0][1].legend(handles=[didntLike, smallDoses, largeDoses])
    axs[1][0].legend(handles=[didntLike, smallDoses, largeDoses])
    #显示图片
    plt.show()
コード例 #45
0
ファイル: cluster ucb.py プロジェクト: leonpalafox/CodigoLeon
    'Estado_Civil_tesis'
],
             axis=1)

dt = dt.fillna(0)
print dt
#asignamo el numero de clusters
k = 2
model = KM(n_clusters=k)
model = model.fit(dt)
labels = model.labels_

centro = model.cluster_centers_

colors = ['blue', 'red', 'green', 'black']
y = 0
for x in labels:
    plt.scatter(dt.iloc[y, 0], dt.iloc[y, 1], color=colors[x])
    y += 1

for x in range(k):
    lines = plt.plot(centro[x, 0], centro[x, 1], 'kx')
    plt.setp(lines, ms=15.0)
    plt.setp(lines, mew=2.0)

title = ('n de clus(k)={}').format(k)
plt.title(title)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
コード例 #46
0
m = 25

for day in days:
    results = range(10)
    data = []
    for result in results:
        a = random.choice(range(10))
        data.append([m - a, m, m + a])
    ax = plt.subplot(1, 7, days.index(day) + 1)
    medianprops = dict(linestyle=None, linewidth=0)
    plt.boxplot(data,
                notch=0,
                sym='',
                vert=0,
                whis=0,
                medianprops=medianprops,
                patch_artist=True,
                boxprops=dict(facecolor='blue', color='white'))
    plt.xlabel(day)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.yaxis.set_ticks([0])
    ax.xaxis.set_ticks([0])
    #	ax.yaxis.set_ticks([10,20,30,40])
    ax.xaxis.set_ticklabels('')
    plt.setp(ax.get_yticklabels(), visible=False)

plt.subplots_adjust(wspace=1)
plt.show()
コード例 #47
0
ファイル: analysis.py プロジェクト: vaibhav-shr/Master-Thesis
def pod_recommender(throughput_list, s_rate, pod, thr, sr, incorrect_pod,
                    n_req, ttime, accu, totime):
    if len(incorrect_pod) == 3 or len(incorrect_pod) == 2:
        print(
            "The application's reource profile is imperfect and SLAs can not be verified!"
        )
        return
    elif len(incorrect_pod) == 1:
        diff = error(throughput[1], throughput[2])
        diff = round(diff, 2)
        print(
            "The maximum verified throughput is with 10 pods. The difference in throughputs of 10 and 20 pods is "
            + str(diff) + "%")
        print("The maximum throughput for this application is " +
              str(throughput[1]))
        return

    X_list = [list(a) for a in zip(throughput_list, s_rate)]
    Y_list = pod

    x_list = [list(a) for a in zip(thr, sr)]

    poly = PolynomialFeatures(degree=2)
    X_ = poly.fit_transform(X_list)
    X_test = poly.fit_transform(x_list)

    lg = LinearRegression()
    lg.fit(X_, Y_list)

    y_pred = lg.predict(X_test)
    if y_pred[0] < 0:
        y_pred[0] = 1
    rec_pods = math.ceil(y_pred[0])

    plt.rcParams.update({'font.size': 20})

    fig, axs = plt.subplots(4, 1, sharex=True, sharey=False)
    axs[0].plot(lg.predict(poly.fit_transform(X_list)),
                throughput_list,
                color='r',
                marker='o',
                label='throughput')
    axs[0].set(ylabel='Maximum Throughput')

    axs[1].plot(lg.predict(poly.fit_transform(X_list)),
                ttime,
                color='r',
                marker='o',
                label='Total time')
    axs[1].set(ylabel='Total Response Time (s)')

    axs[2].plot(lg.predict(poly.fit_transform(X_list)),
                s_rate,
                color='g',
                marker='o',
                label='Success rate')
    axs[2].set(ylabel='Maximum Success Rate')

    axs[3].bar(lg.predict(poly.fit_transform(X_list)),
               n_req,
               color='r',
               label='Total requests')
    axs[3].set(ylabel='Number of Requests', xlabel='Number of Pods')

    for ax in axs:
        ax.set_facecolor('#edf8fd')
        ax.grid()
        ax.legend(loc='upper left')

    fig.subplots_adjust(hspace=0)
    plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)

    fig.set_size_inches(25, 25)
    fig.set_dpi(80)

    plt.savefig('diagrams_loc.png')

    #print("The recommended number pods for your SLA is: "+str(rec_pods))
    n_time = len(ttime)
    sum_time = sum(ttime)
    avg_time = sum_time / n_time

    # If time is there and this is the first prediction, a accuracy can't be calculated (see description of accuracy in readme)
    if (totime - sum_time) > avg_time:
        if n_time == 3:
            print("The recommended number of pods for your SLA is: " +
                  str(rec_pods))
            print("The following verification test may be conducted:")

            req = []
            for filename in glob.glob(os.path.join(path + "/1_pod/", '*.csv')):
                filename = os.path.basename(filename)
                req.append(int(filename.split('_')[0]))
                req.sort()
            rec_pods_requests = req[0] * rec_pods
            print(
                str(rec_pods) + " pods -----> " + str(rec_pods_requests) +
                " requests")
            next_req = int((rec_pods_requests / 2) + rec_pods_requests)
            print(
                str(rec_pods) + " pods -----> " + str(next_req) + " requests")
            Y_list.append(rec_pods)
            Y_list.sort()
            with open("data.txt", "wb") as fp:
                pickle.dump(Y_list, fp)
                pickle.dump(rec_pods, fp)
            new_folder = path + "/" + str(rec_pods) + "_pod/"
            try:
                os.mkdir(new_folder)
                os.mkdir(new_folder + "resource/")
            except OSError:
                print("Folder creation failed")

        # if this is not the first prediction we also calculate accuracy
        elif n_time > 3:
            with open("data.txt", "rb") as fp:
                pod_list = pickle.load(fp)
                last = pickle.load(fp)
            acc_err = error(rec_pods, last)
            acc_err = 100 - acc_err
            if acc_err > accu[0]:
                print("The recommended number pods for your SLA is: " +
                      str(rec_pods) + ". The accuracy being " + str(acc_err) +
                      "%" + " for your SLA.")
                return

            print("The recommended number of pods for your SLA is: " +
                  str(rec_pods))
            print("The following verification test may be conducted:")

            req = []
            for filename in glob.glob(os.path.join(path + "/1_pod/", '*.csv')):
                filename = os.path.basename(filename)
                req.append(int(filename.split('_')[0]))
                req.sort()
            rec_pods_requests = req[0] * rec_pods
            print(
                str(rec_pods) + " pods -----> " + str(rec_pods_requests) +
                " requests")
            next_req = int((rec_pods_requests / 2) + rec_pods_requests)
            print(
                str(rec_pods) + " pods -----> " + str(next_req) + " requests")
            Y_list.append(rec_pods)
            Y_list.sort()
            with open("data.txt", "wb") as fp:
                pickle.dump(Y_list, fp)
                pickle.dump(rec_pods, fp)
            new_folder = path + "/" + str(rec_pods) + "_pod/"
            try:
                os.mkdir(new_folder)
                os.mkdir(new_folder + "resource/")
            except OSError:
                print("Folder creation failed")

    # if no time left
    elif (totime - sum_time) < avg_time:
        if n_time == 3:
            print("The recommended number of pods for your SLA is: " +
                  str(rec_pods))
            print("Due to time constraints it can not be verified")
            return

        elif n_time > 3:
            with open("data.txt", "rb") as fp:
                pod_list = pickle.load(fp)
                last = pickle.load(fp)
            acc_err = error(rec_pods, last)
            acc_err = 100 - acc_err
            if acc_err > accu[0]:
                print("The recommended number of pods for your SLA is: " +
                      str(rec_pods) + ". The accuracy being " + str(acc_err) +
                      "%" + " for your SLA.")
            else:
                print(
                    "The recommended number of pods for your SLA is: " +
                    str(rec_pods) +
                    ". Due to time constraints it can not be verified further."
                )
コード例 #48
0
def lineplot_per_interval(df,
                          y,
                          hue,
                          y_title="",
                          start_year=DEFAULT_MIN_YEAR,
                          save_to_file=True,
                          filetype="pdf",
                          legend_loc="upper right",
                          hue_order=None,
                          legend_title="Snapshot rank",
                          estimator=np.median):
    fig, ax = plt.subplots()
    if not y_title:
        if hue:
            y_title = hue.title()
        else:
            y_title = ""

    # filter by start year
    df = df[df.year_season >= str(start_year)]

    set_plot_params()

    if hue:
        try:
            fig = sns.lineplot(data=df,
                               y=y,
                               x=INTERVAL_COL_NAME,
                               hue=hue,
                               style=hue,
                               hue_order=hue_order,
                               estimator=estimator,
                               ci=95)
        except:
            markers = list(range(1, len(hue_order) + 1))
            print(markers)
            fig = sns.lineplot(data=df,
                               y=y,
                               x=INTERVAL_COL_NAME,
                               style=hue,
                               hue=hue,
                               dashes=False,
                               markers=markers,
                               hue_order=hue_order)
        set_legend(ax, legend_title, legend_loc)
        plt.setp(fig.get_legend().get_texts(),
                 fontsize='10')  # for legend text
        plt.setp(fig.get_legend().get_title(),
                 fontsize='10')  # for legend text

    else:
        fig = sns.lineplot(data=df,
                           y=y,
                           x=INTERVAL_COL_NAME,
                           estimator=estimator)

    set_x_ticks(df)

    #fig.set(xlabel='Interval', ylabel=y_title)
    ax.set_xlabel('Interval')
    ax.set_ylabel(y_title, fontsize=10)

    # fig.set_title(y_title + " per interval")
    fig_filename = "lineplot_%s.%s" % ("_".join(
        y_title.replace("%", "pct").replace("(", "").replace(
            ")", "").lower().split()), filetype)
    if save_to_file:
        save_figure(fig, fig_filename)
    return fig
コード例 #49
0
# Abtasten der drei Funktionen
x1_S = A_1 * cos(f_1 * 2 * pi * t_S + phi_1)

#%% Figure 1: Zeitbereich
fig1 = plt.figure(1)  # neue Grafik
plt.clf()
ax1 = fig1.add_subplot(111)
ax1.plot(t, x1, linewidth=3, color='r', label='$\phi_1$')

#plt.legend()

[ml, sl, bl] = ax1.stem(t_S, x1_S)
plt.setp(ml,
         'markerfacecolor',
         'k',
         marker='o',
         markeredgecolor='k',
         markeredgewidth=1.0,
         markersize=10)
plt.setp(sl, linewidth=1, color='k')
plt.setp(bl, 'color', 'white')

title_string = '$f_{sig} = %.3g \mathrm{\,Hz},\, f_{S} = %.4g \mathrm{\,Hz}$' \
                 % (f_1,f_S)
#plt.title('Analoge Signale mit gleicher Abgetasteten\n' + title_string, fontsize = 18)
#plt.title(title_string, fontsize = 16, ha = 'center', va = 'bottom')
ax1.set_xlabel(r'$t \, \mathrm{/ \, s\,} \rightarrow $', fontsize=16)
ax1.set_ylabel(r'$x \, \mathrm{/ \, V\,} \rightarrow $', fontsize=16)
ax1.text(.03,
         0.97,
         r'$F_{sig} = f_{sig} / f_S =  %.2g$' % (f_1 / f_S),
コード例 #50
0
# Now plot cosine functions for frequencies -2pi/N * k
N = 128
xvalues = np.linspace(0, N, N)
for u in range(0, N):
     yvalues = np.sin(2 * np.pi * u / N * xvalues)
     plt.plot(xvalues, yvalues, 'r')
     # plt.savefig('/Users/ciezcm15/Documents/Project1/sin'+str(u)+'.png', bbox_inches='tight')
     # plt.clf()
     # print('saving image ' + str(u) + ' out of ' + str(N))

# Compute the 1-D Fourier transform of colData
F_colData = np.fft.fft(colData)

xvalues = np.linspace(-int(len(colData)/2), int(len(colData)/2)-1, len(colData))
markerline, stemlines, baseline = plt.stem(xvalues, np.fft.fftshift(np.abs(F_colData)), 'g')
plt.setp(markerline, 'markerfacecolor', 'g')
plt.setp(baseline, 'color','r', 'linewidth', 0.5)
plt.show()
# cv2.savefig('C:/Users/ciezcm15/Documents/Project1/FourierCoef.JPG', plt)

# Fourier Function complex function magnitudes
print(np.abs(F_colData))

# create the x and y coordinate arrays (here we just use pixel indices)
xx, yy = np.mgrid[0:grayImg.shape[0], 0:grayImg.shape[1]]
# create the figure
fig = plt.figure()
# ax = fig.gca(projection='3d')
#ax.plot_surface(xx, yy, grayImg, rstride=1, cstride=1, cmap=plt.cm.gray, linewidth=0)
#plt.show()
# cv2.savefig('C:/Users/ciezcm15/Documents/Project1/2DFourier.JPG', plt)
コード例 #51
0
ファイル: zad9.py プロジェクト: kamillon/wd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('zamowienia.csv', header=0, sep = ";")

p = df.groupby(['Sprzedawca']).agg({"idZamowienia":['count']})
sprzedawcy = p.index.values
zamowienia = [p.values[y][0] for y in range(len(p.values))]
Explode = [0 for i in range(len(p.index.values))]
Explode[2]=0.1
plt.figure(figsize=(10,6))

wedges, texts, autotexts = plt.pie(zamowienia, explode=Explode, shadow=True, labels=sprzedawcy,
                                   autopct=lambda pct: "{:.1f}%".format(pct), textprops=dict(color="black"))
plt.setp(autotexts, size=10, weight="bold")
plt.legend(title='Sprzedawcy', loc='best', bbox_to_anchor=(1.5,1))
plt.show()
コード例 #52
0
#
axes.violinplot(all_data2, showmeans=False, showmedians=True)

axes.set_title('Abdomen')
axes.set_ylim([3, 17.7])

# plot box plot
#axes[1].boxplot(all_data)
#axes[1].set_title('box plot')

# adding horizontal grid lines
#for ax in axes:
axes.yaxis.grid(True)
axes.set_xticks([y + 1 for y in range(len(all_data))])
axes.set_xlabel('')
axes.axhline(y=15, c="hotpink", zorder=0, linestyle='-',
             linewidth=2)  ## ACR DIR
axes.axhline(y=25, c="orangered", zorder=2, linestyle='--', linewidth=2)  ## EU
axes.set_ylabel('CTDI$_{\mathrm{VOL}}$ (mGy)')

# add x-tick labels
plt.setp(axes,
         xticks=[y + 1 for y in range(len(all_data))],
         xticklabels=[
             'Trifasico\nHígado', 'UroTAC', 'Abdomen', 'Dinámico\nPáncreas',
             'Pélvis'
         ])

#fig.savefig('ctdi_abd_levels.svg', format='svg')
plt.show()
コード例 #53
0
because this changes the tick Formatter, which is shared among all
axes.  But you can alter the visibility of the labels, which is a
property

  setp( ax2.get_xticklabels(), visible=False)
"""

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.01, 5, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = np.exp(-t)
s3 = np.sin(4 * np.pi * t)
ax1 = plt.subplot(311)
plt.plot(t, s1)
plt.setp(ax1.get_xticklabels(), fontsize=6)

# share x only
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)
# make these tick labels invisible
plt.setp(ax2.get_xticklabels(), visible=False)

# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)
plt.show()
コード例 #54
0
ファイル: stock.py プロジェクト: aaronz/study
def pandas_candlestick_ohlc(dat, stick="day", otherseries=None):
    """
    :param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo"
    :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period
    :param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines
 
    This will show a Japanese candlestick plot for stock data stored in dat, also plotting other series if passed.
    """
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    alldays = DayLocator()  # minor ticks on the days
    dayFormatter = DateFormatter('%d')  # e.g., 12

    # Create a new DataFrame which includes OHLC data for each period specified by stick input
    transdat = dat.loc[:, ["Open", "High", "Low", "Close"]]
    if (type(stick) == str):
        if stick == "day":
            plotdat = transdat
            stick = 1  # Used for plotting
        elif stick in ["week", "month", "year"]:
            if stick == "week":
                transdat["week"] = pd.to_datetime(transdat.index).map(
                    lambda x: x.isocalendar()[1])  # Identify weeks
            elif stick == "month":
                transdat["month"] = pd.to_datetime(transdat.index).map(
                    lambda x: x.month)  # Identify months
            transdat["year"] = pd.to_datetime(transdat.index).map(
                lambda x: x.isocalendar()[0])  # Identify years
            grouped = transdat.groupby(list(set(
                ["year",
                 stick])))  # Group by year and other appropriate variable
            plotdat = pd.DataFrame({
                "Open": [],
                "High": [],
                "Low": [],
                "Close": []
            })  # Create empty data frame containing what will be plotted
            for name, group in grouped:
                plotdat = plotdat.append(
                    pd.DataFrame(
                        {
                            "Open": group.iloc[0, 0],
                            "High": max(group.High),
                            "Low": min(group.Low),
                            "Close": group.iloc[-1, 3]
                        },
                        index=[group.index[0]]))
            if stick == "week": stick = 5
            elif stick == "month": stick = 30
            elif stick == "year": stick = 365

    elif (type(stick) == int and stick >= 1):
        transdat["stick"] = [
            np.floor(i / stick) for i in range(len(transdat.index))
        ]
        grouped = transdat.groupby("stick")
        plotdat = pd.DataFrame({
            "Open": [],
            "High": [],
            "Low": [],
            "Close": []
        })  # Create empty data frame containing what will be plotted
        for name, group in grouped:
            plotdat = plotdat.append(
                pd.DataFrame(
                    {
                        "Open": group.iloc[0, 0],
                        "High": max(group.High),
                        "Low": min(group.Low),
                        "Close": group.iloc[-1, 3]
                    },
                    index=[group.index[0]]))

    else:
        raise ValueError(
            'Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer'
        )

    # Set plot parameters, including the axis object ax used for plotting
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'):
        weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
        ax.xaxis.set_major_locator(mondays)
        ax.xaxis.set_minor_locator(alldays)
    else:
        weekFormatter = DateFormatter('%b %d, %Y')
    ax.xaxis.set_major_formatter(weekFormatter)

    ax.grid(True)

    # Create the candelstick chart
    candlestick_ohlc(ax,
                     list(
                         zip(list(date2num(plotdat.index.tolist())),
                             plotdat["Open"].tolist(),
                             plotdat["High"].tolist(), plotdat["Low"].tolist(),
                             plotdat["Close"].tolist())),
                     colorup="black",
                     colordown="red",
                     width=stick * .4)

    # Plot other series (such as moving averages) as lines
    if otherseries != None:
        if type(otherseries) != list:
            otherseries = [otherseries]
        dat.loc[:, otherseries].plot(ax=ax, lw=1.3, grid=True)

    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(),
             rotation=45,
             horizontalalignment='right')

    plt.show()
コード例 #55
0
ファイル: candlestick.py プロジェクト: vsjha18/finplots
def candlestick_plot(df,
                     smas=[100, 50, 5, 10],
                     style=style,
                     figsize=(18, 10),
                     rsi_setup=dict(period=14),
                     macd_setup=dict(slow=26, fast=12, ema=8),
                     bbands_setup=dict(period=20, multiplier=2),
                     sstoch_setup=dict(period=14, smoothing=3)):
    """ plot candlestick chart """

    fig = plt.figure(figsize=figsize,
                     facecolor=style.face_color)  # 18, 10 for full screen

    # create main axis for charting prices
    ax1 = plt.subplot2grid((10, 4), (0, 0),
                           rowspan=6,
                           colspan=4,
                           axisbg=style.axis_bg_color)

    if 'volume' not in df:
        df['volume'] = np.zeros(len(df))


#   times = pd.date_range('2014-01-01', periods=l, freq='1d')
    df.date = pd.to_datetime(df.date)
    df.date = [mdates.date2num(d) for d in df.date]

    df = df[::-1]

    payload = df[['date', 'open', 'high', 'low', 'close', 'volume']].values
    candlestick_ohlc(ax1,
                     payload,
                     width=0.5,
                     colorup=style.cdl_up_color,
                     colordown=style.cdl_down_color)

    annotate_max(ax1, df)

    ax1.grid(True, alpha=style.grid_alpha, color=style.grid_color)
    plt.ylabel('Stock Price', color=style.label_color)

    # determines number of points to be displayed on x axis
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(50))
    ax1.yaxis.set_major_locator(mticker.MaxNLocator(15))

    # determines format of markers on the xaxis
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%y'))

    # label color
    ax1.yaxis.label.set_color(style.label_color)

    # tick params color
    ax1.tick_params(axis='y', colors=style.tick_color)

    # spine colors
    ax1.spines['bottom'].set_color(style.spine_color)
    ax1.spines['top'].set_color(style.spine_color)
    ax1.spines['left'].set_color(style.spine_color)
    ax1.spines['right'].set_color(style.spine_color)

    # make the x tick label invisible
    plt.setp(ax1.get_xticklabels(), visible=False)

    # OVERLAY SIMPLE MOVING AVERAGES
    for idx, period in enumerate(smas):
        ax1 = plot_sma(ax1, df, period=period, color=style.sma_colors[idx])

    # OVERLAY BOLLINGER BAND
    ax1 = plot_bollinger_bands(ax1,
                               df,
                               period=bbands_setup['period'],
                               multiplier=bbands_setup['multiplier'])

    # OVERLAY VOLUME
    # it is important to plot volume after the simple moving
    # average to avoid a warning message 'no labelled objects found'
    if 'volume' in df:
        ax1 = plot_volume(ax1, df)

    # show tick params on right axis as well
    ax1.tick_params(labelright=True)

    # RELATIVE STRENGTH INDEX
    ax_rsi = plt.subplot2grid((10, 4), (9, 0),
                              rowspan=1,
                              colspan=4,
                              sharex=ax1,
                              axisbg=style.axis_bg_color)
    plot_rsi(ax_rsi, df, period=rsi_setup['period'])

    # MOVING AVERAGE CONVERGENCE DIVERGENCE
    ax_macd = plt.subplot2grid((10, 4), (8, 0),
                               rowspan=1,
                               colspan=4,
                               sharex=ax1,
                               axisbg=style.axis_bg_color)

    ax_macd = plot_macd(ax_macd,
                        df,
                        slow=macd_setup['slow'],
                        fast=macd_setup['fast'],
                        ema=macd_setup['ema'])

    # SLOW STOCHASTIC
    # create axis for charting prices
    ax_sstoch = plt.subplot2grid((10, 4), (6, 0),
                                 rowspan=2,
                                 colspan=4,
                                 sharex=ax1,
                                 axisbg=style.axis_bg_color)

    ax_sstoch = plot_slow_stochastic(ax_sstoch,
                                     df,
                                     period=sstoch_setup['period'],
                                     smoothing=sstoch_setup['smoothing'])

    #
    # ema_fast, ema_slow, macd = moving_average_convergence_divergence(df.close)
    # ema9 = exponential_moving_average(macd, nema)
    #
    # # plot_macd(ax_macd, df, style=style, slow=macd_setup['slow'], fast=macd_setup['fast'], ema=macd_setup['nema'] )
    # ax3.plot(df.index, macd, linewidth=2, color='lime')
    # ax3.plot(df.index, ema9, linewidth=2, color='hotpink')
    #
    #
    #
    #
    # # FROM HERE
    # # prune the yaxis
    # ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=3, prune='lower'))
    #
    # # print text
    # ax3.text(0.015, 0.95, 'MACD 12,26,9', va='top', color='white', transform=ax3.transAxes)
    # # put markers for signal line
    # # following line needs as many stuff as there are markers
    # # hence we have commented this out.
    # # ax_rsi.axes.yaxis.set_ticklabels([30, 70])
    #
    # #ax3.set_yticks([])
    #
    # # provide the yaxis range
    # #ax3.set_ylim(0, 100)
    #
    # # draw horizontal lines
    # # ax3.axhline(70, color=style.rsi_signal_line_color, alpha=style.rsi_signal_line_alpha)
    # # ax3.axhline(50, color=style.rsi_signal_line_color, alpha=style.rsi_signal_line_alpha)
    # #ax3.axhline(0, color='w')
    # # ax3.axhline(30, color=style.rsi_signal_line_color, alpha=style.rsi_signal_line_alpha)
    #
    # # fill color
    # div = macd - ema9
    # ax3.fill_between(df.index, div, 0, facecolor='deepskyblue', edgecolor='w', alpha=0.3)
    #
    # # ax3.fill_between(df.index, rsi_data, 30, where=(rsi_data<=30), facecolor=style.rsi_oversold_color)
    # # label color
    # ax3.yaxis.label.set_color(style.label_color)
    #
    # # spine colors
    # ax3.spines['bottom'].set_color(style.spine_color)
    # ax3.spines['top'].set_color(style.spine_color)
    # ax3.spines['left'].set_color(style.spine_color)
    # ax3.spines['right'].set_color(style.spine_color)
    #
    # # tick params color
    # ax3.tick_params(axis='y', colors='w')
    # ax3.tick_params(axis='x', colors='w')
    #
    # # plot the grids.
    # ax3.grid(True, alpha=style.grid_alpha, color=style.grid_color)
    # plt.ylabel('MACD', color=style.label_color)
    # plt.setp(ax3.get_xticklabels(), visible=False)
    # # Till here

    # make the labels a bit rotated for better visibility
    for label in ax_rsi.xaxis.get_ticklabels():
        label.set_rotation(45)

    # adjust the size of the plot
    #plt.subplots_adjust(left=0.10, bottom=0.19, right=0.93, top=0.95, wspace=0.20, hspace=0.0)
    plt.subplots_adjust(left=0.07,
                        bottom=0.10,
                        right=0.97,
                        top=0.95,
                        wspace=0.20,
                        hspace=0.0)

    # plt.xlabel('Date', color=style.label_color)
    plt.suptitle('Stock Price Chart', color=style.label_color)

    plt.show()
コード例 #56
0
    for p in players:
        sub = data[data['pid'] == p]
        for j in list(sub.index):
            if sub['state'][j] != 'exploiting' and sub['have_been_nearby'][j]:
                times += [int(np.log(sub['since_nearby'][j] + 1))]
                states += [sub['state'][j]]

df = pd.DataFrame(dict(time=times, state=states))

state_names = ['exploring', 'copying']
x = []
y = dict([(s, []) for s in state_names])

print
print 'states as a function of time'
for val in sorted(list(set(df['time']))):
    states = df[df['time'] == val]['state']
    x += [val]
    for s in state_names:
        y[s] += [np.mean(states == s)]

plt.figure()
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)
for s in state_names:
    plt.plot(x, y[s], label=s)
plt.xlabel('Log Time Since Last with Group', fontsize=24)
plt.ylabel('Probability Given Not Exploiting', fontsize=24)
pylab.legend(loc='upper left')
plt.setp(plt.gca().get_legend().get_texts(), fontsize='20')
plt.show()
コード例 #57
0
'#d9d9d9',
'#bc80bd',
'#ccebc5',
'#ffed6f']

fig1, ax1 = plt.subplots()
#fig1.patch.set_alpha(0.3)
patches, texts, autotexts = ax1.pie(y_col, explode=None, autopct='%1.1f%%',
shadow=False, startangle=90, colors=cols1)#,labels=x_col)#,labels=x_col)
ax1.axis('equal')
#fig1.set_facecolor('w') #change canvas color
plt.title("Self Signed Certifcates",y=1.05)

#Change font size
proptease = fm.FontProperties()
#proptease.set_size(8)
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)


#Shrink current axis by 20%
#box = ax1.get_position()
#ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height])


#plt.legend(patches, zip(x_col,percent), loc="best",bbox_to_anchor=(0.8, 0.5)) display name and percentage
plt.legend(patches, x_col,loc='best')#,bbox_to_anchor=(0.8, 0.5),prop={'size':8})

#plt.show() # Equal aspect ratio ensures that pie is drawn as a circle.
plt.savefig("SelfSigned.svg")
コード例 #58
0
    axes[length_data_list[j]].set_yscale('log')

    axes[length_data_list[j]].set_ylabel(
        f'ST-{satellite_no_st} Proton\nFlux [pfu]',
        fontname="Arial",
        fontsize=12)
    applyPlotStyle()

# plt.xlabel('Time [UT]', fontname="Arial", fontsize = 12)

# myFmt = mdates.DateFormatter('%m/%d\n%H:%M')
ax = plt.gca()
# ax.xaxis.set_major_formatter(myFmt)

plt.setp(ax.xaxis.get_majorticklabels(),
         rotation=0,
         horizontalalignment='center')
# plt.suptitle(f'Space Weather Monitor]', fontname="Arial", fontsize = 14) #, y=1.04,
#plt.tight_layout()

plt.subplots_adjust(wspace=0, hspace=0, top=0.91)
plt.savefig('corr_fluence_20180322.png', format='png', dpi=900)

#plt.savefig('omni_test_legacy.png', format='png', dpi=900)
'''
if event_option == 'yes':
	plt.savefig(f'xflare_events/omni_test_{event_date}.png', format='png', dpi=900)

if save_plot_option == 'yes' and len(option_bin_set) <= 4:
	plt.savefig(f'xflare_events/omni_test_{event_date}.png', format='png', dpi=900)
コード例 #59
0
def plotAttribute(cur, planners, attribute, typename):
    """Create a plot for a particular attribute. It will include data for
    all planners that have data for this attribute."""
    labels = []
    measurements = []
    nanCounts = []
    if typename == 'ENUM':
        cur.execute('SELECT description FROM enums where name IS "%s"' %
                    attribute)
        descriptions = [t[0] for t in cur.fetchall()]
        numValues = len(descriptions)
    for planner in planners:
        cur.execute('SELECT %s FROM runs WHERE plannerid = %s AND %s IS NOT NULL' \
            % (attribute, planner[0], attribute))
        measurement = [t[0] for t in cur.fetchall() if t[0] != None]
        if measurement:
            cur.execute('SELECT count(*) FROM runs WHERE plannerid = %s AND %s IS NULL' \
                % (planner[0], attribute))
            nanCounts.append(cur.fetchone()[0])
            labels.append(planner[1])
            if typename == 'ENUM':
                scale = 100. / len(measurement)
                measurements.append(
                    [measurement.count(i) * scale for i in range(numValues)])
            else:
                measurements.append(measurement)

    if not measurements:
        print('Skipping "%s": no available measurements' % attribute)
        return

    plt.clf()
    ax = plt.gca()
    if typename == 'ENUM':
        width = .5
        measurements = np.transpose(np.vstack(measurements))
        colsum = np.sum(measurements, axis=1)
        rows = np.where(colsum != 0)[0]
        heights = np.zeros((1, measurements.shape[1]))
        ind = range(measurements.shape[1])
        for i in rows:
            plt.bar(ind, measurements[i], width, bottom=heights[0], \
                color=matplotlib.cm.hot(int(floor(i * 256 / numValues))), \
                label=descriptions[i])
            heights = heights + measurements[i]
        xtickNames = plt.xticks([x + width / 2. for x in ind],
                                labels,
                                rotation=30)
        ax.set_ylabel(attribute.replace('_', ' ') + ' (%)')
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
        props = matplotlib.font_manager.FontProperties()
        props.set_size('small')
        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), prop=props)
    elif typename == 'BOOLEAN':
        width = .5
        measurementsPercentage = [sum(m) * 100. / len(m) for m in measurements]
        ind = range(len(measurements))
        plt.bar(ind, measurementsPercentage, width)
        xtickNames = plt.xticks([x + width / 2. for x in ind],
                                labels,
                                rotation=30)
        ax.set_ylabel(attribute.replace('_', ' ') + ' (%)')
    else:
        if int(matplotlibversion.split('.')[0]) < 1:
            plt.boxplot(measurements, notch=0, sym='k+', vert=1, whis=1.5)
        else:
            plt.boxplot(measurements,
                        notch=0,
                        sym='k+',
                        vert=1,
                        whis=1.5,
                        bootstrap=1000)
        ax.set_ylabel(attribute.replace('_', ' '))
        xtickNames = plt.setp(ax, xticklabels=labels)
        plt.setp(xtickNames, rotation=25)
    ax.set_xlabel('Motion planning algorithm')
    ax.yaxis.grid(True,
                  linestyle='-',
                  which='major',
                  color='lightgrey',
                  alpha=0.5)
    if max(nanCounts) > 0:
        maxy = max([max(y) for y in measurements])
        for i in range(len(labels)):
            x = i + width / 2 if typename == 'BOOLEAN' else i + 1
            ax.text(x,
                    .95 * maxy,
                    str(nanCounts[i]),
                    horizontalalignment='center',
                    size='small')
    plt.show()
コード例 #60
0
def demo_simple_image(ax):
    Z, extent = get_demo_image()

    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    cb = plt.colorbar(im)
    plt.setp(cb.ax.get_yticklabels(), visible=False)