Example #1
0
def compile_scatter_plot_3d(args):
    bytes = args['tp_sizes'][0]
    tracers = args['tracers']
    res_dir = '/home/mogeb/git/benchtrace/trace-client/'
    values = defaultdict(list)

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

    fname = res_dir + 'none_' + str(bytes) + 'bytes_1process.hist'
    with open(fname, 'r') as f:
        legend = f.readline()
    legend = legend.split(',')
    i = 0
    for tracer in tracers:
        fname = res_dir + tracer + '_' + str(bytes) + 'bytes_1process.hist'
        values[tracer] = np.genfromtxt(fname, delimiter=',', skip_header=1, names=legend,
                                       dtype=None)

    fontP = FontProperties()
    fontP.set_size('small')

    for tracer in tracers:
        ax.scatter(values[tracer]['cache_misses'], values[tracer]['Instructions'],
                   values[tracer]['latency'])
    plt.title('Latency according to cache_misses and instructions')
    ax.set_xlabel('cache_misses')
    ax.set_ylabel('Instructions')
    ax.set_zlabel('latency')
    plt.legend(prop=fontP)
    plt.show()
Example #2
0
def make_overview_plot(filename, title, noip_arrs, ip_arrs):
    plt.title("Inner parallelism - " + title)

    
    plt.ylabel('Time (ms)', fontsize=12)

    x = 0
    barwidth = 0.5
    bargroupspacing = 1.5

    for z in zip(noip_arrs, ip_arrs):
        noip,ip = z
        noip_mean,noip_conf = conf_stats(noip)
        ip_mean,ip_conf = conf_stats(ip)

        b_noip = plt.bar(x, noip_mean, barwidth, color='r', yerr=noip_conf, ecolor='black', alpha=0.7)
        x += barwidth

        b_ip = plt.bar(x, ip_mean, barwidth, color='b', yerr=ip_conf, ecolor='black', alpha=0.7)
        x += bargroupspacing

    plt.xticks([0.5, 2.5, 4.5], ['50k', '100k', '200k'], rotation='horizontal')

    fontP = FontProperties()
    fontP.set_size('small')

    plt.legend([b_noip, b_ip], \
        ('no inner parallelism', 'inner parallelism'), \
        prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
   
    plt.ylim([0,62000])
    plt.savefig(output_file(filename))
    plt.clf()
	def plot_np_simple(x_labels, x_values_np, y_values_np, x_label, y_label, title, nb_x_labels, style):
		x = np.arange(len(y_values_np))
		
		fig, ax = plt.subplots()
		if style != None:
			ax.plot(x_values_np, y_values_np, style)
		else:
			ax.plot(x_values_np, y_values_np)
		
		
		
			
		
		
		plt.xlabel(x_label)
		plt.ylabel(y_label)
		plt.title(title)
		fontP = FontProperties()
		fontP.set_size('small')
		plt.legend(loc='lower right', prop=fontP)
		
		if x_labels != None:
			labels = np.array(x_labels)
			jump_step = len(labels)/nb_x_labels

			
			label_indexes = np.arange(1,len(labels),jump_step)
			
			for (X, Z) in zip(x[label_indexes], labels[label_indexes]):
				ax.annotate('{}'.format(Z), xy=(X,0), xytext=(X, (-0.1*y_max)), rotation=90, ha='center', size=10,
							textcoords='data')
		
		fig.tight_layout(pad=4)
		plt.draw()
def main():

    # Write a part to put image directories into "groups"
    source_dirs = [
        '/home/sbraden/400mpp_15x15_clm_wac/mare/',
        '/home/sbraden/400mpp_15x15_clm_wac/pyro/',
        '/home/sbraden/400mpp_15x15_clm_wac/imps/',
        '/home/sbraden/400mpp_15x15_clm_wac/mare_immature/'
        ]

    for directory in source_dirs:
        
        print directory
        groupname = os.path.split(os.path.dirname(directory))[1]
        print groupname
        # read in LROC WAC images
        wac_img_list = iglob(directory+'*_wac.cub')
        # read in Clementine images
        clm_img_list = iglob(directory+'*_clm.cub')

        make_cloud_plot(wac_img_list, colorloop.next(), groupname)

    fontP = FontProperties()
    fontP.set_size('small')
    #plt.legend(loc='upper left', fancybox=True, prop=fontP, scatterpoints=1)
    #plt.axis([0.70, 0.86, 0.90, 1.15],fontsize=14)
    plt.axis([0.60, 0.90, 0.90, 1.20],fontsize=14)
    plt.axes().set_aspect('equal')
    # THIS next line does not get called:
    plt.margins(0.20) # 4% add "padding" to the data limits before they're autoscaled
    plt.xlabel('WAC 320/415 nm', fontsize=14)
    plt.ylabel('CLM 950/750 nm', fontsize=14)
    plt.savefig('lunar_roi_cloud_plot.png', dpi=300)
    plt.close()
Example #5
0
    def __init__(self, xy, s, size=None, prop=None,
                 _interpolation_steps=1, usetex=False,
                 *kl, **kwargs):
        """
        Create a path from the text. No support for TeX yet. Note that
        it simply is a path, not an artist. You need to use the
        PathPatch (or other artists) to draw this path onto the
        canvas.

        xy : position of the text.
        s : text
        size : font size
        prop : font property
        """

        if prop is None:
            prop = FontProperties()

        if size is None:
            size = prop.get_size_in_points()

        self._xy = xy
        self.set_size(size)

        self._cached_vertices = None

        self._vertices, self._codes = self.text_get_vertices_codes(
                                            prop, s,
                                            usetex=usetex)

        self._should_simplify = False
        self._simplify_threshold = rcParams['path.simplify_threshold']
        self._has_nonfinite = False
        self._interpolation_steps = _interpolation_steps
Example #6
0
def frequency_plots(filename, xs_list, normalize=False, color='b', labels=['Plot1'], title=None, ylim=None, xlim=None, xlabel=None, ylabel=None):
  '''Take lists of lists of values, create multiple frequency tables and plot multiple lines'''
  ccolors = colors(len(xs_list))
  plt.clf()
  plt.figure().set_size_inches(25,15)
  ax = plt.subplot(111)
  for i, xs in enumerate(xs_list):
    dik = Counter(xs)
    if normalize:
      diksum = sum(dik.values())
      dik = {k:float(v)/diksum for k,v in dik.iteritems()}
    dicty = zip(*sorted(dik.iteritems()))
    ax.plot(dicty[0], dicty[1], color=ccolors[i], label=labels[i])
    ax.scatter(max(dik, key=dik.get), dik[max(dik, key=dik.get)], color=ccolors[i])
  if xlabel:
    ax.xlabel(xlabel)
  if ylabel:
    ax.ylabel(ylabel)
  if ylim:
    plt.ylim(ylim)
  else:
    plt.ylim(ymin=0)
  if xlim:
    plt.xlim(xlim)
  if title:
    plt.title(title)
  box = ax.get_position()
  ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])  
  from matplotlib.font_manager import FontProperties
  fontP = FontProperties()
  fontP.set_size('small')
  ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), prop=fontP)
  plt.savefig('%s' % filename)
Example #7
0
def test_suptitle_fontproperties():
    from matplotlib.font_manager import FontProperties
    fig, ax = plt.subplots()
    fps = FontProperties(size='large', weight='bold')
    txt = fig.suptitle('fontprops title', fontproperties=fps)
    assert txt.get_fontsize() == fps.get_size_in_points()
    assert txt.get_weight() == fps.get_weight()
Example #8
0
def make_legend(labels, colors, output_file):
    """ Hack to generate a legend as a separate image.  A dummy plot
        is created in one figure, and its legend gets saved to an
        output file.

        Inputs:
        labels - text labels for the legend
        colors - list of colors for the legend (same length as labels)
        output_file - filename for the resulting output figure

        Outputs:
        (None - output figure is written to output_file)

    """
    if len(labels) != len(colors):
        raise ValueError("Lists of labels and colors "
                         " should have the same length")
    fig = plt.figure()
    font_prop = FontProperties()
    font_prop.set_size('xx-large')
    font_prop.set_family('sans-serif')
    seperate_legend = plt.figure(figsize=(5, 3.5))
    ax = fig.add_subplot(111)
    N = len(labels)
    # Make a dummy pie chart so we can steal its legend
    wedges, texts = ax.pie([100/N]*N, colors=colors)
    seperate_legend.legend(wedges, labels, 'center',
                           prop=font_prop, frameon=False)
    seperate_legend.savefig(output_file)
Example #9
0
def plot_all(wells, errors=None, do_legend=True, legend_position=0.8):
    """Plots all of the timecourses in the dict.

    Parameters
    ----------
    wells : dict of timecourse data of the type returned by read_wallac.
    """
    for wellname, wellval in wells.iteritems():
        if errors is None:
            plot(wellval[TIME], wellval[VALUE], label=wellname)
        else:
            errorbar(wellval[TIME], wellval[VALUE],
                    yerr=errors[wellname][VALUE], label=wellname)

    # Label the axes and add a legend
    xlabel('Time') # TODO: automatically determine seconds or minutes, etc.
    ylabel('Value')

    if do_legend:
        fontP = FontProperties()
        fontP.set_size('small')
        ax = gca()
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * legend_position,
                         box.height])
        legend(loc='upper left', prop=fontP, ncol=1, bbox_to_anchor=(1, 1),
             fancybox=True, shadow=True)
def grafico(dicionario, info):
    fontP = FontProperties()
    fontP.set_size("small")
    marcadores = ["+", ".", "o", "*", "p", "s", "x", "D", "h"]
    eixo_y = []
    eixo_x = range(1, 9)
    nome_bairro = []
    legendas = []

    for i in dicionario.items():
        eixo_y.append(i[1])
        nome_bairro.append(i[0])

    for i in nome_bairro:
        legendas.append(info[i[6:]])

    for i in range(len(eixo_x)):
        plt.plot(eixo_x, eixo_y[i], label=legendas[i])

    plt.ylabel("numero de roubos")
    plt.xlabel("meses")
    art = []
    lgd = plt.legend(loc=9, bbox_to_anchor=(0.5, -0.1), ncol=2, prop=fontP)
    art.append(lgd)
    plt.savefig("grafico_roubos2015.png", additional_artists=art, bbox_inches="tight")
def plot_gradient_over_time(points, get_grad_over_time):
    fig = plt.figure(figsize=(6.5, 4))
    # Remove the plot frame lines. They are unnecessary chartjunk.    
    ax = plt.subplot(111)    
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    # ax.xaxis.set_major_locator(plt.MultipleLocator(1.0))
    # ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    # ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
    # ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
    # ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')
    # ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')
    # ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')
    # ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')
    ax.grid(b=True, which='major', linewidth=0.75, linestyle=':', color='0.75')
    ax.yaxis.set_ticks_position('none')
    ax.xaxis.set_ticks_position('none')
    for wx, wRec, c in points:
        grad_over_time = get_grad_over_time(wx, wRec)
        x = np.arange(1, grad_over_time.shape[1]+1, 1)
        plt.plot(x, np.sum(grad_over_time, axis=0), c+'.-', label='({0}, {1})'.format(wx, wRec), linewidth=1, markersize=8)
    plt.xlim(1, grad_over_time.shape[1])
    plt.xticks(x)
    plt.gca().invert_xaxis()
    plt.yscale('symlog')
    plt.yticks([10**8, 10**6, 10**4, 10**2, 0, -10**2, -10**4, -10**6, -10**8])
    plt.xlabel('time k')
    plt.ylabel('gradient ')
    plt.title('Unstability of gradient in backward propagation.\n(backpropagate from left to right)')
    leg = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False, numpoints=1)
    leg_font = FontProperties()
    leg_font.set_size('x-large')
    leg.set_title('$(w_x, w_{rec})$', prop=leg_font)
Example #12
0
    def _get_3d_plot(self, label_stable=True):
        """
        Shows the plot using pylab.  Usually I won"t do imports in methods,
        but since plotting is a fairly expensive library to load and not all
        machines have matplotlib installed, I have done it this way.
        """
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d.axes3d as p3
        from matplotlib.font_manager import FontProperties

        fig = plt.figure()
        ax = p3.Axes3D(fig)
        font = FontProperties()
        font.set_weight("bold")
        font.set_size(20)
        (lines, labels, unstable) = self.pd_plot_data
        count = 1
        newlabels = list()
        for x, y, z in lines:
            ax.plot(x, y, z, "bo-", linewidth=3, markeredgecolor="b", markerfacecolor="r", markersize=10)
        for coords in sorted(labels.keys()):
            entry = labels[coords]
            label = entry.name
            if label_stable:
                if len(entry.composition.elements) == 1:
                    ax.text(coords[0], coords[1], coords[2], label)
                else:
                    ax.text(coords[0], coords[1], coords[2], str(count))
                    newlabels.append("{} : {}".format(count, latexify(label)))
                    count += 1
        plt.figtext(0.01, 0.01, "\n".join(newlabels))
        ax.axis("off")
        return plt
Example #13
0
 def _show_3d_plot(self):
     '''
     Shows the plot using pylab.  Usually I won't do imports in methods,
     but since plotting is a fairly expensive library to load and not all 
     machines have matplotlib installed, I have done it this way.
     '''
     import matplotlib.pyplot as plt
     import mpl_toolkits.mplot3d.axes3d as p3
     from matplotlib.font_manager import FontProperties
     fig = plt.figure()
     ax = p3.Axes3D(fig)
     font = FontProperties()
     font.set_weight('bold')
     font.set_size(20)
     (lines, labels, unstable) = self.pd_plot_data
     count = 1
     newlabels = list()
     for x, y, z in lines:
         ax.plot(x, y, z, 'bo-', linewidth=3, markeredgecolor='b', markerfacecolor='r', markersize=10)
     for coords in sorted(labels.keys()):
         entry = labels[coords]
         label = entry.name
         if len(entry.composition.elements) == 1:
             # commented out options are only for matplotlib 1.0.  Removed them so that most ppl can use this class.
             ax.text(coords[0], coords[1], coords[2], label)#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font)
         else:
             ax.text(coords[0], coords[1], coords[2], str(count))#, horizontalalignment=halign, verticalalignment=valign, fontproperties=font)
             newlabels.append(str(count) + " : " + label)
             count += 1
     plt.figtext(0.01, 0.01, '\n'.join(newlabels))
     ax.axis('off')
     plt.show()
Example #14
0
def time_hist(results,title=None,style='bmh'):
    '''
    Draw an histogram of the time results with basic stats added in the corner
    '''
    # reset style first (if style has been changed before running the script)
    plt.style.use('classic')
    plt.style.use(style)
    plt.style.use(r'.\large_font.mplstyle')
        
    fig, ax = plt.subplots(figsize=(10,8))
    ax.hist(results['Time'],bins=range(15,61))
    ax.set_xlim(15,60)
    ax.set_xlabel('Time (min)',size='x-large')
    ax.set_ylim(0,40)
    ax.set_ylabel('Count',size='x-large')
    plt.title(title)
    
    # add stats in a box in the corner
    stats = results['Time'].describe()
    stats_text = "Count  = {:.0f}\nMean   = {}\nMedian = {}\nMin    = {}\nMax    = {}".format(
                stats['count'],
                minutes_to_timeString(stats['mean']),
                minutes_to_timeString(stats['50%']),
                minutes_to_timeString(stats['min']),
                minutes_to_timeString(stats['max']))
                
    font0 = FontProperties()
    font0.set_family('monospace')
    ax.text(47,30,stats_text,fontsize=14,fontproperties=font0,bbox=dict(facecolor='white'))
Example #15
0
def ageGrade_hist(results,title=None,style='bmh'):
    '''
    Draw an histogram of the Age Grade results with basic stats added in the corner
    '''
    # reset style first (if style has been changed before running the script)
    plt.style.use('classic')
    plt.style.use(style)
    plt.style.use(r'.\large_font.mplstyle')
        
    fig, ax = plt.subplots(figsize=(10,8))
    ax.hist(results['Age Grade']*100,bins=np.arange(0,100,5),color='#A60628')
    #ax.set_xlim(15,60)
    ax.set_xlabel('Age Grade %',size='x-large')
    #ax.set_ylim(0,40)
    ax.set_ylabel('Count',size='x-large')
    plt.title(title)
    
    # add stats in a box
    stats = results['Age Grade'].describe()
    stats.iloc[1:]=stats.iloc[1:]*100
    stats_text = "Count  = {:.0f}\nMean   = {:.1f}%\nMedian = {:.1f}%" +\
                "\nMin    = {:.1f}%\nMax    = {:.1f}%"
    stats_text = stats_text.format(stats['count'],
                                   stats['mean'],stats['50%'],
                                   stats['min'],stats['max'])
    font0 = FontProperties()
    font0.set_family('monospace')
    ax.text(0.72,0.75,stats_text,fontsize=14,fontproperties=font0,
            bbox=dict(facecolor='white'),transform=ax.transAxes)
Example #16
0
    def __init__(self,Model_suite,**input_parameters):
        
        self.working_directory = '.'
        self.station_listfile = None
        self.station_xyfile = None
        self.Model_suite = Model_suite
        self.modeltype = 'model'
        self.fig_width = 1.
        self.ax_width = 0.03
        self.ax_height = 0.8
        self.ax_bottom = 0.1
        self.plot_spacing = 0.02
        self.ylim = [6,0]
        self.title_type = 'single'
        self.titles = {'minmax':'Minimum and maximum resistivity, $\Omega m$',
                       'aniso':'Anisotropy in resistivity',# (maximum/minimum resistivity)
                       'strike':'Strike angle of minimum resistivity'}#, $^\circ$
        self.xlim = {'minmax':[0.1,1000],
                     'aniso':[0,20],
                     'strike':[0,180]}
        self.fonttype = 'serif'
        self.label_fontsize = 8
        self.title_fontsize = 12
                     
        for key in input_parameters.keys():
            setattr(self,key,input_parameters[key])

        font0 = FontProperties()
        font = font0.copy()
        font.set_family(self.fonttype)
        self.font = font
            
        self.working_directory = os.path.abspath(self.working_directory)
Example #17
0
def create_plot(plot_title, datasets, offset, count, output_path):
    x = 0

    for dataset_path in datasets:

        first,average,conf = statistics(dataset_path, offset, count)

        b_first = plt.bar(x, first, 0.5, color='b')
        x += 0.5

        b_average = plt.bar(x, average, 0.5, color='r', yerr=conf, ecolor='black')
        x += 1.5

    plt.title("benchmark: " + plot_title)

    plt.xlabel('Dataset', fontsize=12)
    plt.ylabel('Time', fontsize=12)

    plt.xticks([0.5, 2.5, 4.5, 6.5, 8.5], ['10', '100', '1000', '10000', '100000'], rotation='horizontal')

    # Create graph legend
    fontP = FontProperties()
    fontP.set_size('small')

    plt.legend([b_first, b_average], \
        ('first query time', 'average time of other queries'), \
        prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
    
    # Plot to file
    plt.savefig(output_path)
    plt.clf()
 def bargraph(self):
     ind = np.arange(int(self.count))
     width = 0.25
     data = reportDB().selectSql(self.LATE_FIVE_SQL)
     errorsList = tuple(error[0] for error in data)[::-1]
     passedList = tuple(right[1] for right in data)[::-1]
     failedList = tuple(fail[2] for fail in data)[::-1]
     startTime = tuple(runtime[3] for runtime in data)[::-1]
     fig, ax = plt.subplots()
     ax.set_ylabel(u'个数')
     ax.set_title(u'最近%s次测试结果柱状图' % self.count)
     ax.set_xticks(ind+width)
     ax.set_xticklabels(startTime,rotation=18, fontsize='small')
     rectError = ax.bar(ind, errorsList, width, color='r')
     rectFail = ax.bar(ind+width, failedList, width, color='y')
     rectPass = ax.bar(ind+2*width, passedList, width, color='g')
     fontP = FontProperties()
     fontP.set_size('small')
     for e_rect in rectError:
         height = e_rect.get_height()
         ax.text(e_rect.get_x()+e_rect.get_width()/2., 1.05*height, '%d'%int(height),
                 ha='center', va='bottom')
     for f_rect in rectFail:
         height = f_rect.get_height()
         ax.text(f_rect.get_x()+f_rect.get_width()/2., 1.05*height, '%d'%int(height),
                 ha='center', va='bottom')
     for p_rect in rectPass:
         height = p_rect.get_height()
         ax.text(p_rect.get_x()+p_rect.get_width()/2., 0.8*height, '%d'%int(height),
                 ha='center', va='bottom')
     ax.legend( (rectError[0], rectPass[0], rectFail[0]), (u'错误', u'通过', u'失败'),prop = fontP)
     plt.savefig('E:\\apk\huodong\\tr\\pic\\bargraph')
Example #19
0
def main():
    dataset = VOCBboxDataset(year='2007', split='test')
    models = [
        ('Faster R-CNN', FasterRCNNVGG16(pretrained_model='voc07')),
        ('SSD300', SSD300(pretrained_model='voc0712')),
        ('SSD512', SSD512(pretrained_model='voc0712')),
    ]
    indices = [29, 301, 189, 229]

    fig = plot.figure(figsize=(30, 30))
    for i, idx in enumerate(indices):
        for j, (name, model) in enumerate(models):
            img, _, _ = dataset[idx]
            bboxes, labels, scores = model.predict([img])
            bbox, label, score = bboxes[0], labels[0], scores[0]

            ax = fig.add_subplot(
                len(indices), len(models), i * len(models) + j + 1)
            vis_bbox(
                img, bbox, label, score,
                label_names=voc_bbox_label_names, ax=ax
            )

            # Set MatplotLib parameters
            ax.set_aspect('equal')
            if i == 0:
                font = FontProperties()
                font.set_family('serif')
                ax.set_title(name, fontsize=35, y=1.03, fontproperties=font)
            plot.axis('off')
            plot.tight_layout()

    plot.show()
Example #20
0
    def initGraph(self):
        """ initalize graph to draw spans """

        self.trial = 1
        self.sbs = {}
        self.sbs['Lever'] = ScatterBrain('Lever','#3399FF','o')
        self.sbs['Mark'] = ScatterBrain('Mark','#000000','x')
        for i in range(0,5):
            name = 'aTaste%d'%i
            self.sbs[name] = ScatterBrain(name,uv.TasteColors[i],'s')
            name2 = 'mTaste%d'%i
            self.sbs[name2] = ScatterBrain(name2,uv.TasteColors[i],'s',False)
        
        self.figure = Figure(dpi=100,figsize=(5,5.5))
        self.axes = self.figure.add_subplot(111)
        print 'X.trial', X.trialDuration
        self.axes.axis([0,X.trialDuration,0,1.5])
        self.axes.set_xlabel('time (s)')
        
        self.drawSpans(True)
        
        LText = FontProperties()
        LText.set_size("small")
        
        
        self.axes.legend((self.sbs['Lever'].getPlot(self.axes),self.sbs['Mark'].getPlot(self.axes),
                          self.sbs['aTaste1'].getPlot(self.axes),self.sbs['mTaste1'].getPlot(self.axes)),
                         ("Lever Press","Time Marked", "Reward","Manual Reward"),
                         prop=LText, fancybox=True, bbox_to_anchor=(0., 1.02, 1., .102), loc=1, ncol=2, mode="expand", borderaxespad=0)
        
        self.canvas = FigureCanvas(self, -1, self.figure)
def plotProfile(plotname, data):
    ''' Plot a profile of the colors'''
    dtc=None
    if args.window:
        dt=numpy.transpose(data)
        for i in range(dt.shape[0]):
            dt[i]=movingAverage(dt[i], args.window)

        dtc=numpy.transpose(dt)
    else:
        dtc=data

    fontP = FontProperties()
    fontP.set_size('small')
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.plot(dtc)
    #ax.set_xticklabels(xlabels, rotation=45, fontproperties=fontP)
    #ax.set_xlabel('Image number in the series')
    ax.set_ylabel('Reef colors')
    box = ax.get_position()
    #ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
    #ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height])
    ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height *0.85])
    header=["blue", "green", "red"]

    ax.legend((header), loc='upper center', bbox_to_anchor=(0.5, -0.10), ncol=4, prop=fontP)
    fig.savefig(plotname)
Example #22
0
File: utils.py Project: meyyar/WoC
    def add_plot(title, plots, min_class_label, max_class_label):
        colors = ["r", "y"]
        place = [0, 0.35]

        Utils.subplot += 1
        # fig = .figure()
        ax = Utils.figure.add_subplot(Utils.subplot)

        Utils.figure.subplots_adjust(hspace=0.75, wspace=0.5)
        ax.set_title(title)
        ax.set_xticks(np.arange(8))
        for i in xrange(len(plots)):
            item = plots[i]
            if item["xlim"] != None:
                ax.set_xlim(item["xlim"])
            if item["ylim"] != None:
                ax.set_ylim(item["ylim"])
            ax.set_xlabel(item["xlabel"])
            ax.set_ylabel(item["ylabel"])
            ax.bar(
                np.arange(min_class_label, max_class_label + 1) + place[i],
                item["y_values"],
                0.35,
                color=colors[i],
                label=item["label"],
            )

        handles, labels = ax.get_legend_handles_labels()
        fontP = FontProperties()
        fontP.set_size("small")
        Utils.figure.legend(handles, labels, loc="upper right", prop=fontP)
Example #23
0
def basic_skysurvey_plot_setup(from_plane=ephem.degrees('0')):
    # # EmulateApJ columnwidth=245.26 pts
    # fig_width_pt = 246.0
    # inches_per_pt = 1.0 / 72.27
    # golden_mean = (sqrt(5.) - 1.0) / 2.0
    # fig_width = fig_width_pt * inches_per_pt
    # fig_height = fig_width * golden_mean * 1.5
    # fig_size = [fig_width, fig_height]

    fig = plt.figure()
    ax = fig.add_subplot(111)  # , aspect="equal")

    handles = []  # this handles the creation of the legend properly at the end of plotting
    labels = []
    handles, labels = plot_galactic_plane(handles, labels)
    # handles, labels = plot_ecliptic_plane(handles, labels)
    handles, labels = plot_invariable_plane(handles, labels, from_plane)

    fontP = FontProperties()
    fontP.set_size('small')  # make the fonts smaller
    plt.xlabel('RA (deg)')
    plt.ylabel('Declination (deg)')
    plt.grid(True, which='both')
    # plot_fanciness.remove_border(ax)

    return handles, labels, ax, fontP
def save_graph(go_dict, chart_type, level, parser):
	fontP = FontProperties()
	fontP.set_size('small')
	# The slices will be ordered and plotted counter-clockwise.
	figure = plt.figure(figsize=(10,10))
	
	labels = go_dict.keys()
	sizes = [parser.go_term_by_name_dict.get(x)[0].encountered_count for x in go_dict]
	#sizes = go_dict.values() 	
	#print (chart_type)
	#print (zip(labels, sizes))
	#print (sum(sizes))
	plt.title('Graph Level %s Pie Chart [%s]' % (level, chart_type))
	total = sum(sizes)
	
	labels = [l+" "+str(float(s)/total * 100)[0:4]+"%  ("+ str(s) + ")" for l,s in zip(labels, sizes)]

	patches, texts = plt.pie(sizes, startangle=90)
	plt.legend(patches, labels, prop = fontP, loc="best")
	# Set aspect ratio to be equal so that pie is drawn as a circle.
	plt.axis('equal')
	#plt.tight_layout()
	#plt.show()



	print (chart_type)
	out = [str(x) + "\t" + str(parser.go_term_by_name_dict.get(x)[0].encountered_count) for x in go_dict]

	for x in out:
		print (x)
	print ("\n")	


	figure.savefig(chart_type+"_level_"+level+'.png',aspect='auto',dpi=100)
def plot_benchmarks(runs, out_file="output.eps", dpi=1200):
    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties

    fontP = FontProperties()
    fontP.set_size("small")

    lines, densities = regroup_runs(runs)

    for line in lines:
        method = line["method"]
        condensation = line["2x2"]
        ys = [line[x] for x in densities]

        plt.plot(
            densities,
            ys,
            METHOD_SHAPE[method] + COND_SHAPE[condensation],
            color=METHOD_COLOR[method],
            label=method + COND_LEGEND[condensation],
        )

    plt.xlabel("density, %")
    plt.ylabel("CPU time, ms")

    if "2000" not in out_file:
        lgd = plt.legend(loc=2, prop=fontP)
    else:
        lgd = plt.legend(loc=2, bbox_to_anchor=(1, 1), prop=fontP)
    plt.grid(True)
    plt.savefig(out_file, bbox_extra_artists=(lgd,), bbox_inches="tight", format=out_file[-3:], dpi=dpi)
Example #26
0
def topic_distribution(name = None, study = None, order = None, **options):
    '''Given a model p_z,p_w_z,p_d_z, we can plot the document's distribution
    using p(z|d) = normalized((p(d|z)*p(z))) '''
    
    m = microbplsa.MicrobPLSA()
    m.open_model(name = name, study = study, **options) #get model from the results file
    #return document's distribution
    p_z_d = m.model.document_topics()
    
    Z,N =p_z_d.shape #number of samples
    if order is not None:
        p_z_d = p_z_d[:,order]
    n = np.arange(N)
    width = 25.0/float(N) #scale width of bars by number of samples
    p = [] #list of plots
    colors = plt.cm.rainbow(np.linspace(0, 1, Z))    
    
    Lab = Labelling(m, ignore_continuous = False)
    Lab.metadata(non_labels = ['BarcodeSequence'])
    R = Lab.correlate()
    labels_r = Lab.assignlabels(R,num_labels = 1)
    labels, r = zip(*labels_r)
    labels = [l.replace('(','\n(') for l in labels]
    
    #sort and organize labels and topics so they are always plotted in the same order
    labelsUnsorted = zipper(labels,range(0,Z))
    labelsUnsorted.sort()
    labels, Zrange = zip(*labelsUnsorted)
    Zrange = list(Zrange)
    p.append(plt.bar(n, p_z_d[Zrange[0],:], width, color=colors[0], linewidth = 0))
    height = p_z_d[Zrange[0],:]
    for i,z in enumerate(Zrange[1:]):
        p.append(plt.bar(n, p_z_d[z,:], width, color=colors[i+1], bottom=height, linewidth = 0))
        height += p_z_d[z,:]
    
    
    plt.ylabel('Probability P(z|d)')
    plt.xlabel('Sample')
    plt.title('Sample\'s topic distribution')
    #plt.xticks(np.arange(0,width/2.0,N*width), ['S'+str(n) for n in range(1,N)])

    topiclegend = ['Topic' + str(Zrange[labels.index(l)]+1) + ': '+ l + '\n ('+ str(r[Zrange[labels.index(l)]]) + ')' for l in labels]
    fontP = FontProperties()
    if N >60:
        fontP.set_size('xx-small')
    else: fontP.set_size('small')
    ax = plt.subplot(111)
    ratio = float(N)*0.5
    ax.set_aspect(ratio)
    ax.tick_params(axis = 'x', colors='w') #remove tick labels by setting them the same color as background
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, 0.5, box.height])

    if order is not None:
        plt.xticks(n, order, size = 'xx-small')
    if Z > 12: 
        columns = 2
    else: columns = 1
    plt.legend(p, topiclegend, prop = fontP, title = 'Topic Label', loc='center left', bbox_to_anchor=(1, 0.5), ncol = columns)
    return plt
Example #27
0
def graph(fil):
    heap, time , free = np.loadtxt(fil, delimiter=',', unpack=True)

    fig,ax1 = plt.subplots(dpi=120, figsize=(7,7))
    ax2 = plt.twinx()

    ax1.set_ylabel("Allocation time ($ms$)",color = 'blue')
    ax1.set_xlabel("Initial heap size ($MB$)")

    ax2.set_ylabel("Free space on heap ($MB$)",color = 'green')
    ax2.set_xlabel("Initial heap size ($MB$)")


    p1,= ax1.plot(heap,time, label='Time taken to allocate large array')
    p2,= ax2.plot(heap,free , label='Free space on heap' ,color = 'green')


    plt.title('Scala Fragmentation tolerance')

    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')


    lines =[p1,p2]

    plt.legend(lines, [l.get_label() for l in lines],prop = fontP ,loc =9)

    name =  fil.split('.')[0]
    name = name +".png"

    plt.savefig(name)
Example #28
0
def PlotSensitivityAndPPVGraphs(sensitivityDict, ppvDict, graphTitle, xAxisTitle, index, graphFileName):
	
	sensDremeMeanValues, sensDremeErrorValues, sensKspectrumMeanValues, sensKspectrumErrorValues, labels = parseResults.GetMeanAndStdErrorValues(sensitivityDict, index);
	ppvDremeMeanValues, ppvDremeErrorValues, ppvKspectrumMeanValues, ppvKspectrumErrorValues, labels = parseResults.GetMeanAndStdErrorValues(ppvDict, index);

	import matplotlib
	matplotlib.use('Agg')
	
	from matplotlib import pyplot as plt	
	matplotlib.rcParams.update({'font.size': 8})

	#Two subplots, the axes array is 1-d
	fig, (ax1, ax2) = plt.subplots(nrows=2)
	eb1, eb2, eb3, eb4 = sensitivity_ppv_plot(ax1, graphTitle + " on Sensitivity", sensDremeMeanValues, sensDremeErrorValues, sensKspectrumMeanValues, sensKspectrumErrorValues, labels, xAxisTitle, "Sensitivity");
	eb1, eb2, eb3, eb4= sensitivity_ppv_plot(ax2, graphTitle + " on PPV", ppvDremeMeanValues, ppvDremeErrorValues, ppvKspectrumMeanValues, ppvKspectrumErrorValues, labels, xAxisTitle, "PPV");	

	#ax2.set_xlabel(xAxisTitle)

	handles_ax1, labels_ax1 = ax1.get_legend_handles_labels();
	handles_ax1 = [h[0] for h in handles_ax1];

	from matplotlib.font_manager import FontProperties
	fontP = FontProperties();
	fontP.set_size('small');
	#fig.legend([eb1, eb2, eb3, eb4], ["DREME", "k-spectrum-25", "k-spectrum-50", "k-spectrum-100"], prop = fontP)
	fig.legend(handles_ax1, labels_ax1, loc = 'upper right')
	plt.savefig(graphFileName);
	plt.close(fig)
def make_cross_plot(wac_df, clm_df):
    '''
    x = 320/415
    y = 950/750
    '''

    for index_name in wac_df.index:
        roi_name = index_name[:-4]
        x = wac_df.loc[index_name].values
        y = clm_df.loc[roi_name+'_clm'].values
        x_data = np.ma.masked_array(x[0],np.isnan(x[0]))
        y_data = np.ma.masked_array(y[0],np.isnan(y[0]))
        print roi_name, np.mean(x_data), np.mean(y_data), np.std(x_data), np.std(y_data)
        plt.errorbar(np.mean(x_data), np.mean(y_data), xerr=np.std(x_data),
            yerr=np.std(y_data), marker='o', label=(roi_name), 
            c=colorloop.next())

    rois_rough = pd.read_csv('/home/sbraden/imps_ratio_rough.csv', index_col=0)
    rois_mare = pd.read_csv('/home/sbraden/imps_ratio_mare.csv', index_col=0)

    for roi_name in rois_rough.index:
        ratio = rois_rough.loc[roi_name].values
        plt.scatter(ratio[1], ratio[0], marker='s', c='blue')
    
    for roi_name in rois_mare.index:
        ratio = rois_mare.loc[roi_name].values
        plt.scatter(ratio[1], ratio[0], marker='s', c='red')

    fontP = FontProperties()
    fontP.set_size('small')
    plt.legend(loc='lower right', prop=fontP, numpoints=1)
    plt.xlabel('320/415 nm WAC ratio', fontsize=14)
    plt.ylabel('950/750 nm CLEM ratio', fontsize=14)
    plt.savefig('lunar_roi_cross_plot.png', dpi=300)
    plt.close()
Example #30
0
def plot_markers(data, x_base, name, map, xoff_sgn, width, off_fac,
                 markersize):
    maxD = 0
    ds = {}
    used = []
    font = FontProperties()
    font.set_family('sans-serif')
    font.set_size(10)
    for (kind, subkind, dimval) in data:
        try:
            symb, lab = map[kind][subkind]
        except KeyError:
            raise KeyError("Invalid key for %s symbols"%name)
        used.append((kind, subkind))
        try:
            ds[dimval] += 1
            x_off = xoff_sgn*width*off_fac*(ds[dimval]-1)
        except KeyError:
            ds[dimval] = 1
            x_off = 0
        plot([x_base+x_off], [dimval], symb, markersize=markersize)
        # hack tweaks
    ##            if lab=='C':
    ##                x_off -= width/15
        if lab=='A':
            x_off += width/30
        text(x_base+x_off-width*.15, dimval-width*2., lab,
             fontproperties=font)
        if dimval > maxD:
            maxD = dimval
    return ds, maxD, used
Example #31
0
modpath = os.path.dirname(__file__)
CMAP_DIR = os.path.join(modpath, 'colormap')
r_cmap = form_colormap(os.path.join(CMAP_DIR, 'r_main.txt'), sep=True)
v_cmap = form_colormap(os.path.join(CMAP_DIR, 'v_main.txt'), sep=False)
v_cbar = form_colormap(os.path.join(CMAP_DIR, 'v_cbar.txt'), sep=True)
rhi_cmap_smooth = form_colormap(os.path.join(CMAP_DIR, 'r_smooth.txt'),
                                sep=False,
                                spacing='v')
r_cmap_smooth = form_colormap(os.path.join(CMAP_DIR, 'r_smooth.txt'),
                              sep=False,
                              spacing='v')
zdr_cmap = form_colormap(os.path.join(CMAP_DIR, 'zdr_main.txt'), sep=False)
zdr_cbar = form_colormap(os.path.join(CMAP_DIR, 'zdr_cbar.txt'), sep=True)
kdp_cmap = form_colormap(os.path.join(CMAP_DIR, 'kdp_main.txt'), sep=False)
kdp_cbar = form_colormap(os.path.join(CMAP_DIR, 'kdp_cbar.txt'), sep=True)
cc_cmap = form_colormap(os.path.join(CMAP_DIR, 'cc_main.txt'), sep=False)
cc_cbar = form_colormap(os.path.join(CMAP_DIR, 'cc_cbar.txt'), sep=True)
et_cmap = form_colormap(os.path.join(CMAP_DIR, 'et_main.txt'), sep=False)
et_cbar = form_colormap(os.path.join(CMAP_DIR, 'et_cbar.txt'), sep=True)
vil_cmap = form_colormap(os.path.join(CMAP_DIR, 'vil_main.txt'), sep=True)
vil_cbar = form_colormap(os.path.join(CMAP_DIR, 'vil_cbar.txt'), sep=True)
rf_cmap = cmx.ListedColormap('#660066', '#FFFFFF')
font2 = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\msyh.ttc")
norm1 = cmx.Normalize(0, 75)
norm2 = cmx.Normalize(-35, 27)
norm3 = cmx.Normalize(-1, 0)
norm4 = cmx.Normalize(0, 1)
norm5 = cmx.Normalize(0, 21)
norm6 = cmx.Normalize(-4, 5)
norm7 = cmx.Normalize(260, 360)
norm8 = cmx.Normalize(0, 0.99)
Example #32
0
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html

# This file contains the original convergence work performed on the time integration schemes with
# the convergence data hard-coded into this file. The data includes more time steps than are
# executed in the tests so it is best to keep both.

import matplotlib.pyplot as plt
import numpy as np

# Small font size for the legend
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('x-small')

# Implicit methods - errors reported are L2-errors at time T=1.
# Note: for reasons of expediency, this does not match the end_time
# used in implicit_convergence.i.

# Implicit Euler: dt and L2-error at final time
implicit_euler = [
    .5,
    4.749134e-02,
    .25,
    7.198284e-02,
    .125,
    3.774241e-02,
    .0625,
Example #33
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import trees

decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
font = FontProperties(fname=r"/usr/share/fonts/truetype/wqy/wqy-microhei.tty",
                      size=14)


def plotNode(nodeTxt, centerPt, parentPt, nodeType, font):
    createPlot.ax1.annotate(nodeTxt,xy=parentPt,xycoords='axes fraction',\
    xytext=centerPt,textcoords='axes fraction',\
    va="center",ha="center",bbox=nodeType,arrowprops=arrow_args,fontproperties=font)


def createPlot():
    fig = plt.figure(1, facecolor='white')
    fig.clf()
    axprops = dict(xticks=[], yticks=[])
    #createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)    #no ticks
    createPlot.ax1 = plt.subplot(111, frameon=False)  #ticks for demo puropses
    plotNode(U'决策节点', (0.5, 0.1), (0.1, 0.5), decisionNode, font)
    plotNode(U'叶节点', (0.8, 0.1), (0.3, 0.8), leafNode, font)
    plt.show()


def getNumLeafs(tree):
Example #34
0
import pymc3 as pm
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import theano.tensor as tt
import theano as T

from matplotlib.font_manager import FontProperties
# from pymc3 import get_data
font = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\simsun.ttc", size=14)
np.set_printoptions(precision=0, suppress=True)
# 2017.11.11编辑  可靠性分析项目
# 撰写人:邱楚陌
# ======================================================================
# 数据导入
# companies:代表统一产品的测试地点类别    company:测试地点的搜索索引
# companiesABC:代表不同公司类别           companyABC:公司的搜索索引
# ======================================================================
elec_data = pd.read_csv('XZmulti_3.csv')

# 计算同一公司产品测试地点数目:
companies_num = elec_data.counts.unique()
companies = len(companies_num)  # companies=7, 共7个测试地点
company_lookup = dict(zip(companies_num, range(len(companies_num))))
company = elec_data['company_code'] = elec_data.counts.replace(company_lookup).values  # 加一行数据在XZsingal文件中
# companys = elec_data.counts.values - 1 # 这一句以上面两行功能相同

# 计算不同公司数目
company_ABC = elec_data.company.unique()
# save model
bst.save_model('../model/xgboost.model')
# load model
bst = xgb.Booster()
bst.load_model('../model/xgboost.model')
# 绘制特征的重要性分布
# xgb.plot_importance(bst)
importance = bst.get_fscore(fmap='../result/xgb.fmap')
print(importance)
# 绘制特征的重要性分布
importance = sorted(importance.items(), key=op.itemgetter(1))
df = pd.DataFrame(importance, columns=['feature', 'fscore'])
df['fscore'] = df['fscore'] / df['fscore'].sum()
# 显示特征相对排名
df.plot(kind='barh', x='feature', y='fscore')
font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc', size=12)
font_title = FontProperties(fname='C:\Windows\Fonts\simsun.ttc', size=14)
plt.show()
# get the predicted values
start = time.clock()
predicted_values = bst.predict(data_test)
print('预测耗时:', time.clock() - start, 's')
# evaluation
mape = statistics.mape((y_test+shifted_value)*1000,(predicted_values+shifted_value)*1000)
print('MAPE is ', mape)
mae = statistics.mae((y_test+shifted_value)*1000,(predicted_values+shifted_value)*1000)
print('MAE is ', mae)
mse = statistics.meanSquareError((y_test+shifted_value)*1000,(predicted_values+shifted_value)*1000)
print('MSE is ', mse)
rmse = math.sqrt(mse)
print('RMSE is ', rmse)
    cellText.append(val)

table = box2.table(cellText=cellText, 
                   rowLabels=row, 
                   colWidths=[0.03] * 10,
                   colLabels=col,
                   bbox=(0.1, 0.05, 0.75, 0.8),
                   loc='center')
table.auto_set_font_size(False)
table.set_fontsize(12)
table.scale(1, 1.5)

# Making the row headers and column headers bold
for (row, col), cell in table.get_celld().items():
  if (row == 0) or (col == -1):
    cell.set_text_props(fontproperties=FontProperties(weight='bold'))

# Plotting the Article Info section
box3.axes.get_xaxis().set_visible(False)
box3.axes.get_yaxis().set_visible(False)
box3.set_title('Article Info', ha='right')
box3.text(0.12,0.8,r'# Articles:', ha='left', weight='bold')
box3.text(0.45,0.8,news_info['NumArticles'], ha='left')          
box3.text(0.16,0.58,r'Source:', ha='left', weight='bold')
box3.text(0.39,0.58,news_info['Source'].title(), ha='left')
box3.text(0.09,0.34,r'Date Range:', ha='left', weight='bold')
box3.text(0.39,0.34,news_info['StartDate'], ha='left')
box3.text(0.47,0.21,r'to', ha='left')
box3.text(0.39,0.09,news_info['EndDate'], ha='left')

# Plotting the real-time stock price
Example #37
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

fp = FontProperties(fname='/Library/Fonts/meiryo.ttc', size=14)

if len(sys.argv) != 2:
    print("Usage: $ python %s csvFileName" % sys.argv[0])
    quit()

csvfile = sys.argv[1]

# 1月あたり旅行者
tourlist_dic = {}
for year in range(2012, 2017):
    with open("../tourists_number/FY%d" % year, "r", encoding="utf-8") as f:
        dic = json.load(f)
    for countryData in dic["result"]["changes"]:
        country = countryData["countryName"]
        for i in range(len(countryData["data"])):
            num_qt = countryData["data"][i]
            if num_qt["year"] == year:
                if year == 2012:
                    if num_qt["quarter"] > 2:
                        if num_qt["quarter"] == 3:
                            iteration = 2
# -*- coding: utf-8 -*-
#%% NumPyの読み込み
import numpy as np
#   MatplotlibのPyplotモジュールの読み込み
import matplotlib.pyplot as plt
#   日本語フォントの設定
from matplotlib.font_manager import FontProperties
import sys
if sys.platform.startswith('win'):
    FontPath = 'C:\\Windows\\Fonts\\meiryo.ttc'
elif sys.platform.startswith('darwin'):
    FontPath = '/System/Library/Fonts/ヒラギノ角ゴシック W4.ttc'
elif sys.platform.startswith('linux'):
    FontPath = '/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf'
jpfont = FontProperties(fname=FontPath)
#%% 単利と複利の比較
r = 0.2  # 利率 20%
Maturity = 10  # 運用期間 10年
Simple_Rate = 1.0 + r * np.linspace(0, Maturity, Maturity + 1)
Compound_1year = np.r_[1.0, np.cumprod(np.tile(1.0 + r, Maturity))]
Compound_6month = np.r_[1.0, np.cumprod(np.tile((1.0 + r / 2.0)**2, Maturity))]
Continuous_Rate = np.exp(r * np.linspace(0, Maturity, Maturity + 1))
fig1 = plt.figure(1, facecolor='w')
plt.plot(Simple_Rate, 'k-')
plt.plot(Compound_1year, 'k--')
plt.plot(Compound_6month, 'k-.')
plt.plot(Continuous_Rate, 'k:')
plt.legend([u'単利', u'1年複利', u'半年複利', u'連続複利'],
           loc='upper left',
           frameon=False,
           prop=jpfont)
Example #39
0
File: plot.py Project: rizoic/fluff
def heatmap_plot(data,
                 ind,
                 outfile,
                 tracks,
                 titles,
                 colors,
                 bgcolors,
                 scale,
                 tscale,
                 labels,
                 fontsize,
                 colorbar=True):
    font = FontProperties(size=fontsize / 1.25,
                          family=["Nimbus Sans L", "Helvetica", "sans-serif"])
    label_ratio = 4.0
    # space between heatmaps
    btw_space = 0.02
    plot_width = 1.75 * len(tracks) + btw_space * len(tracks)
    plot_height = 6
    width_ratios = [label_ratio] * len(tracks)
    numplots = len(tracks)
    if labels is not None and len(labels) == len(ind):
        plot_width += 1 / label_ratio
        numplots += 1
        width_ratios += [1]

    # Create figure
    fig = plt.figure(figsize=(plot_width, plot_height))
    # Create subplot layout
    gs = gridspec.GridSpec(
        1,
        numplots,
        width_ratios=width_ratios,
    )

    axes = []
    for i, track in enumerate(tracks):
        c = create_colormap(bgcolors[i % len(bgcolors)],
                            colors[i % len(colors)])
        ax = fig.add_subplot(gs[i])
        ax.set_title(titles[i], fontproperties=font, y=1)
        axes.append(ax)
        cax_mat = ax.pcolormesh(data[track][ind],
                                cmap=c,
                                vmin=0,
                                vmax=scale * tscale[i],
                                rasterized=True)
        hide_axes(ax)
        ylim = ax.get_ylim()
        #fig.colorbar(cax_mat, orientation="horizontal", pad=0.05)
        if colorbar:
            divider = make_axes_locatable(ax)
            ax_cb = divider.new_vertical(size="2%", pad=0.1, pack_start=True)
            fig.add_axes(ax_cb)
            tick_locator = MaxNLocator(nbins=3)
            cbar = fig.colorbar(cax_mat,
                                cax=ax_cb,
                                orientation="horizontal",
                                ticks=tick_locator)
            cbar_labels = cbar.ax.get_xticklabels()
            for lab in cbar_labels:
                lab.set_fontsize(fontsize / 1.25)
            cbar_ticks = cbar.ax.get_xticks()
            if cbar_ticks[0] == 0:
                # if the label is at the start of the colobar
                # move it a bit inside to avoid overlapping
                # with other labels
                cbar_labels[0].set_horizontalalignment('left')
            if cbar_ticks[-1] == 1:
                # if the label is at the end of the colobar
                # move it a bit inside to avoid overlapping
                # with other labels
                cbar_labels[-1].set_horizontalalignment('right')

    if labels is not None and len(labels) == len(ind):
        axcluster = fig.add_subplot(gs[len(tracks)])
        axcluster.axis('off')
        if colorbar:
            divider = make_axes_locatable(axcluster)
            ax_cb = divider.new_vertical(size="2%", pad=0.1, pack_start=True)
            axbl = fig.add_axes(ax_cb)
            axbl.axis('off')
        min_y, max_y = ylim
        s = 0
        axcluster.hlines(y=0,
                         xmin=0,
                         xmax=1,
                         color="grey",
                         linewidth=0.5,
                         alpha=0.5,
                         linestyle='solid')
        labels = np.array(labels)
        # Smaller cluster on the top ([::-1])
        for i in range(max(labels) + 1)[::-1]:
            prev = s
            s += sum(labels == i)
            axcluster.hlines(y=s,
                             xmin=0,
                             xmax=1,
                             color="grey",
                             linewidth=0.5,
                             alpha=0.5,
                             linestyle='solid')
            axcluster.text(0.5, (prev + s) / 2,
                           str(i + 1),
                           verticalalignment="center",
                           horizontalalignment="center",
                           fontproperties=font)

        axcluster.set_ylim(ylim)

    fig.subplots_adjust(wspace=btw_space, hspace=0)
    ext = outfile.split(".")[-1]
    if ext not in ["png", "svg", "ps", "eps", "pdf"]:
        outfile += ".png"
    sys.stderr.write("Saving figure\n")
    # Object orientated pyplot
    fig.savefig(outfile, dpi=600, bbox_inches='tight')
Example #40
0
import io

import base64

import numpy as np
import matplotlib
matplotlib.use('agg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

from matplotlib.font_manager import FontProperties
from matplotlib import rcParams

mpl_lfont = FontProperties()
mpl_lfont.set_size(18)
rcParams['xtick.labelsize'] = rcParams['ytick.labelsize'] = 18

import json
import plotly

from larch.xafs.pre_edge import preedge

PLOTLY_CONFIG = {
    'displaylogo':
    False,
    'modeBarButtonsToRemove':
    ['hoverClosestCartesian', 'hoverCompareCartesian', 'toggleSpikelines']
}


def xafs_plotly(x,
Example #41
0
def draw_picture(vegetables, model):
    v_name = [name[0] for name in vegetables]  # 字典读取key
    zh_price = np.array([price[1][1] for price in vegetables])  # 读取第一列数据
    jp_price = np.array([price[1][0] for price in vegetables])  # 读取第二列数据
    price_mean = jp_price / zh_price  # 求平均值

    plt.style.use('classic')
    # 可以多配置默认设置plt.rcParams
    # plt.rcParams.update({'figure.autolayout': True})
    plt.rcParams['figure.autolayout'] = True
    # plt.rcParams['figure.dpi'] = 150  # 更改默认显示dpi
    # plt.rcParams['savefig.dpi'] = 1000  # 更改默认存储dpi
    plt.rcParams[
        'ytick.direction'] = 'inout'  # 设置坐标轴上的刻度是否突出,'in'、'out'、'inout'。

    font = FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
    fig, ax = plt.subplots(figsize=(8, 4))

    # 个人发现,感觉plt和ax.set_是一个用法,能互换
    if model:
        ax.set_title('中日野菜の値段対比', FontProperties=font, fontsize=20)
        plt.xlabel('値段(円/kg)', FontProperties=font)
        # plt.ylabel('野菜種類', FontProperties=font)
        ax.set_yticks(range(14))  # 效果和plt.yticks()一样
        ax.set_yticklabels(v_name, FontProperties=font, rotation=10)
        # # 和上面两句效果一样
        # plt.yticks(range(14), v_name, FontProperties=font, rotation=10)
        bar_positions = np.arange(14)
        # 如果是水平画图的话,条形的宽度此时就是height,默认0.8
        ax.barh(bar_positions,
                jp_price,
                alpha=0.3,
                height=0.8,
                align='center',
                color='b')
        ax.barh(bar_positions, zh_price, alpha=1, align='center', color='r')

        for i, (x, y) in enumerate(zip(jp_price, bar_positions)):
            plt.text(x, y, '%d' % x, fontsize=10)
            plt.text(x + 150,
                     y,
                     '约%d倍' % price_mean[i],
                     fontsize=10,
                     color='r',
                     FontProperties=font)

        for x, y in zip(zh_price, bar_positions):
            plt.text(x + 20, y, '%d' % x, fontsize=10)

        plt.xlim(0, 2900)
        plt.legend(['日本', '中国'], loc='upper right', fontsize=10, prop=font)
        # fig.savefig('1.png')
        plt.show()
    else:
        x = np.arange(14)
        # plt.xlim(-0.5, 13.5)  # 限制横坐标轴的范围
        # plt.ylim(0, 3000)  # 限制纵坐标轴的范围
        plt.axis([-0.5, 13.5, 0, 2500])  # 一步到位[xmin,xmax,ymin,ymax]
        # bar的横坐标,纵坐标,宽度,是否居中(默认从x起),颜色,透明度
        # 如果是垂直画图的话,条形的宽度此时就是weight,默认0.8,edgecolor条形边的颜色,linewidth条形边的宽度
        plt.bar(x,
                jp_price,
                width=0.8,
                align='center',
                color='g',
                alpha=0.8,
                edgecolor='r',
                linewidth=2)
        plt.bar(x, zh_price, width=0.4, align='center', color='r', alpha=1)

        # 对应坐标,填写相应文本,图片显示乱码的话加上字体路径
        plt.xticks(x,
                   v_name,
                   size='small',
                   rotation=30,
                   fontproperties=font,
                   color='r')
        # plt.yticks(np.arange(0, 2500, 200))  # 设置刻度步长
        plt.xlabel('野菜', fontproperties=font)
        plt.ylabel('値段', fontproperties=font)

        # 图例是有顺序的,按画的先后顺序,loc=0自行找位置,ncol是要显示的函数,frameon=False是去掉框框
        # loc='best', 'upper right', 'center', 'lower left', 'lower right'
        plt.legend(['日本', '中国'],
                   loc=0,
                   ncol=2,
                   fontsize=10,
                   prop=font,
                   frameon=False)
        # plt.grid()  # 加网格线
        plt.show()
def create_plots(args, df):
    import jinja2
    import matplotlib.pyplot as plt
    from palettable import colorbrewer
    from matplotlib.font_manager import FontProperties

    fontP = FontProperties()
    fontP.set_size('xx-small')

    #groups = df.set_index(args.x_axis).groupby([args.group_by])
    groups = df.groupby([args.group_by])
    metrics = list(set(args.metrics) & set(df.keys()))
    colors = take(
        len(metrics),
        cycle(
            chain(
                colorbrewer.qualitative.Dark2_8.mpl_colors,
                colorbrewer.qualitative.Set2_8.mpl_colors,
            )))

    template_loader = jinja2.FileSystemLoader(os.path.join(args.output, '..'))
    template_env = jinja2.Environment(loader=template_loader)
    template_interactive = template_env.get_template(
        'template_fig_interactive.html')
    template_static = template_env.get_template('template_fig_static.html')

    table_interactive = []
    table_static = []

    for group_name, group in groups:

        # always sort by X values
        group = group.sort([args.x_axis])

        if args.fig_title is None:
            fig_title = '%s=%s' % (args.group_by, group_name)
        else:
            fig_title = args.fig_title

        # compute AUC scores
        ys = []
        for metric, color in zip(metrics, colors):
            series = group[metric]
            score = auc_xscaled(group[args.x_axis].values, series.values)
            label = "%s (%.4f)" % (metric, score)
            ys.append((score, metric, label, color))
        ys.sort(reverse=True)

        lbls_old, lbls_new, colors = zip(*ys)[1:4]
        group = group[[args.x_axis] + list(lbls_old)] \
            .set_index(args.x_axis) \
            .rename(columns=dict(zip(lbls_old, lbls_new)))

        # create plots
        fig, ax = plt.subplots()
        group.plot(ax=ax, title=fig_title, color=list(colors))
        ax.set_xlim(*minmaxr(group.index.values))
        ax.set_ylim(0.4, 1.0)
        ax.legend(loc=args.legend_loc, prop=fontP)
        fig_name = 'fig-%s.%s' % (group_name, args.fig_format)
        fig_path = os.path.join(args.output, fig_name)
        csv_name = 'fig-%s.csv' % group_name
        csv_path = os.path.join(args.output, csv_name)
        group.to_csv(csv_path)

        table_interactive.append((
            csv_name,
            args.x_axis,
            "%s=%s" % (args.group_by, group_name),
        ))
        table_static.append(fig_name)

        fig.savefig(fig_path, format=args.fig_format)
        plt.close(fig)

    with open(os.path.join(args.output, 'fig_interactive.html'), 'w') as fh:
        fh.write(template_interactive.render(table=table_interactive))

    with open(os.path.join(args.output, 'fig_static.html'), 'w') as fh:
        fh.write(template_static.render(table=table_static))
Example #43
0
def logo_from_map(all_scores,
                  fontfamily='Arial',
                  size=80,
                  stretch=5,
                  savefile=None):
    if fontfamily == 'xkcd':
        plt.xkcd()
    else:
        mpl.rcParams['font.family'] = fontfamily

    fig, ax = plt.subplots(figsize=(len(all_scores), 2.5))

    font = FontProperties()
    font.set_size(size)
    font.set_weight('bold')

    ax.set_xticks(np.arange(0, len(all_scores) + 1))
    ax.set_yticks(np.arange(-1, 2))
    #     ax.set_xticklabels(range(1,len(all_scores)+1), rotation=90)
    ax.set_yticklabels(np.arange(-1, 2) / stretch)
    seaborn.despine(ax=ax, trim=True)
    ax.spines['bottom'].set_position("center")
    trans_offset = transforms.offset_copy(
        ax.transData, fig=fig, x=0.5, y=0,
        units='dots')  ## as opposed to 'points'

    for index, scores in enumerate(all_scores):

        yshift = 0
        for base, score in sorted([x for x in scores if x[-1] >= 0],
                                  key=lambda x: x[-1]):
            txt = ax.text(
                index + 0.5,
                yshift,
                base,
                transform=trans_offset,
                fontsize=30,
                color=COLOR_SCHEME[base],
                ha='center',
                fontproperties=font,
            )
            txt.set_path_effects([Scale(1.0, stretch * score)])
            fig.canvas.draw()
            window_ext = txt.get_window_extent(txt._renderer)
            yshift += stretch * score

        yshift = 0
        for base, score in sorted([x for x in scores if x[-1] < 0],
                                  key=lambda x: x[-1],
                                  reverse=True):
            yshift += stretch * score
            txt = ax.text(
                index + 0.5,
                yshift,
                base,
                transform=trans_offset,
                fontsize=30,
                color=COLOR_SCHEME[base],
                ha='center',
                fontproperties=font,
            )
            txt.set_path_effects([Scale(1.0, stretch * np.abs(score))])
            fig.canvas.draw()
            window_ext = txt.get_window_extent(txt._renderer)

    plt.gca().axes.get_xaxis().set_visible(False)
    if savefile:
        plt.savefig(savefile, format='eps', bbox='tight')
Example #44
0
Created at home on June 20, 2020

Python final assignment zhuzhuangtu part

@author: yang'yan'qing
"""
import matplotlib as mpl
from matplotlib.font_manager import FontProperties
from collections import Counter
from jieba import posseg as psg
import matplotlib.pyplot as plt

mpl.rcParams['font.sans-serif'] = ['SimHei']  # X 轴可以显示中文
mpl.rcParams['axes.unicode_minus'] = False  # X 轴可以显示中文

font = FontProperties(fname='C:\Windows\Fonts\simkai.ttf', size=14)
f3 = open('./fencihou/忠犬八公的故事.txt', 'r').read()
stopwords = [
    '的', '这种', '这样', '还是', '就是', '这个', '电影', '这部', '一部', '片子', '即使', '虽然',
    '但是', '那个', '看到', '第一次', '一次', '一个', '有些', '什么', "宫崎", "德勒", "可以", "没有",
    "有些", "时候", "真的", "很多", "没有", "不能", "看过", "画片", "哈哈", "不过", "因为", "哗啦",
    "只是"
]

wods = [
    x.word for x in psg.cut(f3)
    if len(x.word) >= 2 and (x.word) not in stopwords
]  #当词语的长度合适且不在无效列表里时进行统计
word_count = Counter(wods)
print(word_count)  #打印出词语及其数量
Example #45
0
# -*- coding: utf-8 -*-
"""
Created on Fri Sep  7 21:08:00 2018

@author: brainbot
"""
import pandas as pd
from matplotlib.font_manager import FontProperties
import seaborn as sns

zhfont = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
sns.set(font=zhfont.get_name())
pdf_ = pd.read_csv("phrase_reg.csv", encoding="gb2312")
print(pdf_)
sns.barplot("phrase", "times", palette="RdBu_r", data=pdf_.head(10))
Example #46
0
#-*- coding: utf-8 -*-
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.figure(figsize=(6, 6))

x = [1, 2, 3, 4, 5, 6, 7, 8]
y = []
for i in x:
    y.append(-(i * i) + i + 3)

plt.plot(x, y)
plt.title(u'测试程序', fontproperties=font)
plt.xlabel(u'x轴', fontproperties=font)
plt.ylabel(u'y轴', fontproperties=font)
plt.grid(True)
plt.show()
Example #47
0
def plot_result(C, deposit):
    """
    Plot calculated thickness distribution and sediment concentration
    
    """
    x_hat = np.linspace(0, 1.0, ngrid)  #grid in transforming coordinate
    x = x_hat * Rw  #x coord in fixed coordinate

    #Formatting plot area
    plt.figure(num=None, figsize=(7, 4), dpi=150, facecolor='w', edgecolor='k')
    plt.subplots_adjust(left=0.10,
                        bottom=0.21,
                        right=0.8,
                        top=0.85,
                        wspace=0.25,
                        hspace=0.2)
    fp = FontProperties(size=9)
    plt.rcParams["font.size"] = 9

    #Line styles
    markerstyle = [
        '*', 'o', 'd', 'x', '+', '<', '|', '8', 1, 6, 's', 'p', ',', '^', 'D',
        'H', '3', '>', 'h', 'v', '1'
    ]
    lstylelist = [':', '-', '--', '-.']

    #Plot thickness distribution
    plt.subplot(2, 1, 1)
    for i in range(cnum):
        d = Ds[i].tolist()[0] * 10**6
        labelname = '{0:.0f} $\mu$m'.format(d)
        #plt.plot(spoints, deposit[i,:], markevery = 10,\
        #    marker = markerstyle[i], linestyle = '-', color = 'k',\
        #    label=labelname,linewidth=0.75)
        #plt.plot(spoints, deposit[i,:], markevery = 10,\
        #    marker = markerstyle[i], linestyle = '-', label=labelname,\
        #    linewidth=0.75)
        plt.plot(spoints, deposit[i,:], linestyle = lstylelist[i],\
                 label=labelname,linewidth=1.0)
    plt.xlabel('Distance (m)')
    plt.ylabel('Deposit Thickness (m)')
    #plt.yscale("log")#set y axis to log scale
    plt.xlim(0, spoints[-1])
    plt.ylim(10**-3, np.max(deposit))
    plt.legend(prop=fp,
               bbox_to_anchor=(1.05, 1),
               loc='upper left',
               borderaxespad=0)

    #Plot spatial distribution of sediment concentration
    plt.subplot(2, 1, 2)
    for i in range(cnum):
        d = Ds[i].tolist()[0] * 10**6
        labelname = '{0:.0f} $\mu$m'.format(d)
        #plt.plot(x, C[i,:]*100., marker = markerstyle[i],\
        #    markevery = 2, linestyle = 'none', color= 'k', label=labelname,\
        #     linewidth=0.75)
        plt.plot(x, C[i,:]*100., linestyle = lstylelist[i], label=labelname,\
                 linewidth=1.0)
    plt.xlabel('Distance (m)')
    plt.ylabel('Concentration (%)')
    plt.yscale("log")  #Set y axis to log scale
    plt.xlim(0, spoints[-1])
    plt.ylim(10**-2, np.max(C * 100))
    plt.legend(prop=fp,
               bbox_to_anchor=(1.05, 1),
               loc='upper left',
               borderaxespad=0)

    plt.show()
Example #48
0
 def find_matplotlib_font(**kw):
     prop = FontProperties(**kw)
     path = findfont(prop, directory=data_path)
     return FontProperties(fname=path)
Example #49
0
    def __init__(self,
                 xy,
                 s,
                 size=None,
                 prop=None,
                 _interpolation_steps=1,
                 usetex=False):
        r"""
        Create a path from the text. Note that it simply is a path,
        not an artist. You need to use the `~.PathPatch` (or other artists)
        to draw this path onto the canvas.

        Parameters
        ----------
        xy : tuple or array of two float values
            Position of the text. For no offset, use ``xy=(0, 0)``.

        s : str
            The text to convert to a path.

        size : float, optional
            Font size in points. Defaults to the size specified via the font
            properties *prop*.

        prop : `matplotlib.font_manager.FontProperties`, optional
            Font property. If not provided, will use a default
            ``FontProperties`` with parameters from the
            :ref:`rcParams <matplotlib-rcparams>`.

        _interpolation_steps : int, optional
            (Currently ignored)

        usetex : bool, default: False
            Whether to use tex rendering.

        Examples
        --------
        The following creates a path from the string "ABC" with Helvetica
        font face; and another path from the latex fraction 1/2::

            from matplotlib.textpath import TextPath
            from matplotlib.font_manager import FontProperties

            fp = FontProperties(family="Helvetica", style="italic")
            path1 = TextPath((12, 12), "ABC", size=12, prop=fp)
            path2 = TextPath((0, 0), r"$\frac{1}{2}$", size=12, usetex=True)

        Also see :doc:`/gallery/text_labels_and_annotations/demo_text_path`.
        """
        # Circular import.
        from matplotlib.text import Text

        prop = FontProperties._from_any(prop)
        if size is None:
            size = prop.get_size_in_points()

        self._xy = xy
        self.set_size(size)

        self._cached_vertices = None
        s, ismath = Text(usetex=usetex)._preprocess_math(s)
        self._vertices, self._codes = text_to_path.get_text_path(prop,
                                                                 s,
                                                                 ismath=ismath)
        self._should_simplify = False
        self._simplify_threshold = rcParams['path.simplify_threshold']
        self._interpolation_steps = _interpolation_steps
Example #50
0
def run_step(step_number, plot_traces=None):
    """Run step current simulation with index step_number"""
    cell = create_cell(add_synapses=False)
    #neuron.h.topology()
    #for sec in neuron.h.allsec():
    #  neuron.h.psection(sec=sec)
    #dend1 = cell.dend[0]
    #neuron.h.psection(sec=dend1)
    #dend2 = cell.dend[60]
    #neuron.h.psection(sec=dend2)
    stimuli = create_stimuli(cell, step_number)
    recordings = create_recordings(cell)
    neuron.h.tstop = 1100  # 3000
    #print neuron.h.dt
    #print('Disabling variable timestep integration')
    neuron.h.cvode_active(0)
    #print('Running for %f ms' % neuron.h.tstop)
    neuron.h.run()
    time = np.array(recordings['time'])  # numpy

    #
    num_axon_sec = 0
    for sec in neuron.h.allsec():
        if (str(sec).split(".")[1][0:2] == "ax"):
            num_axon_sec = num_axon_sec + 1

    print "num_axon_sec = ", num_axon_sec
    #my_neuron = nm.load_neuron('morphology/BC143ax2.CNG.swc') # Pvalb-IRES-Cre_Ai14-236447-02-01-01_543103327_m.CNG.swc') #
    #num_axon_sec = len(nm.get('section_lengths',my_neuron, neurite_type=nm.AXON))

    diam = []
    for j in range(num_axon_sec):  # 111  # range(i)
        diam.append(cell.axon[j].diam)

    tbl = []
    for sec in range(num_axon_sec):
        tbl.append([
            cell.axon[sec], cell.axon[sec].L,
            neuron.h.SectionRef(sec=cell.axon[sec]).parent
        ])

    xy = [
        -1
    ]  #[str(tbl[0][0]).replace("axon[", "").replace("]","")]  # finding the father
    for sec in range(len(tbl) - 1):
        #xy.append(str(tbl[sec+1][2]).replace("cNAC187_L23_LBC_d3f79b893e[0].axon[", "").replace("]",""))
        xy.append(
            str(tbl[sec + 1][2]).replace("bNAC219_L23_LBC_fe2122c75c[0].axon[",
                                         "").replace("]", ""))

    y2 = [
        cell.axon[0].L
    ]  #tbl[0][1]]  # The total length of all fathers (include the current section)! (correction for only one branch)
    for sec in range(len(tbl) - 1):
        y2.append(tbl[sec + 1][1] + y2[int(xy[sec + 1])])

    #y2 = [tbl[0][1]]  # The total length of all fathers (include the current section)!
    #for sec in range(len(tbl)-1):
    #  y2.append(tbl[sec+1][1]+ y2[int(xy[sec+1])])

    direct_child = []  #
    for sec in range(len(tbl)):
        direct_child.append(xy.count(str(sec)))

    total_child = []
    for sec in range(len(tbl) - 2, -1, -1):
        childrn = [i for i, x in enumerate(xy) if x == str(sec + 1)]
        sum_child = direct_child[sec + 1]
        for ch in childrn:
            #print sec+1 , ch , len(tbl)-1-ch , total_child[len(tbl)-1-ch]
            sum_child = sum_child + total_child[len(tbl) - 1 - ch]  #
        total_child.append(sum_child)

    total_child.append(len(tbl) - 1)

    two_childrn = []  # the number of children of each child
    for sec in range(len(tbl)):
        childrn = [
            total_child[len(tbl) - 1 - i] for i, x in enumerate(xy)
            if x == str(sec)
        ]
        temp = [-1, -1]
        for i, ch in enumerate(childrn):
            temp[i] = ch
        two_childrn.append(temp)

    dirc = []
    zrs = [0] * len(tbl)
    for sec in range(len(tbl)):
        if (zrs[int(xy[int(sec)])] == 0):
            zrs[int(xy[int(sec)])] = 1
            dirc.append(0)
        else:
            dirc.append(1)

    pos = [two_childrn[0][0] + 1]
    for sec in range(len(tbl) - 1):
        pp = pos[int(xy[sec + 1])]
        pos.append(
            pp - (two_childrn[sec + 1][1] + 2) * (dirc[sec + 1] == 0) +
            (two_childrn[sec + 1][0] + 2) * (dirc[sec + 1] != 0)
        )  #+ (two_childrn[sec+1][1]==0)*(dirc[sec+1]==0) - (two_childrn[sec+1][0]==0)*(dirc[sec+1]!=0) )

    new_pos = []
    for i in range(len(tbl)):
        k = 0
        for j in pos:
            k = k + 1
            if i == j:
                new_pos.append(k - 1)

    #############
    sp = 11
    xlimbegin = 1000  # 50 #75
    xlimend = 1100  # 130
    fig = pyplot.figure(figsize=(8, 9))  # 8,10
    #ax1 = fig.add_subplot(5,1,1)
    #ax1_plot = ax1.plot(recordings['time'], recordings['soma(0.5)'], color='black')
    #ax1.set_xticks([]) # Use ax2's tick labels
    #ax1.set_xlim([xlimbegin,xlimend])
    #ax1.set_ylim([-90,60])
    ax2 = plt.subplot2grid((sp, 2), (5, 1), rowspan=sp - 5)  #, sharey=ax1)
    ax3 = plt.subplot2grid((sp, 2), (0, 1))
    ax4 = plt.subplot2grid((sp, 2), (1, 1))
    ax5 = plt.subplot2grid((sp, 2), (2, 1))
    ax6 = plt.subplot2grid((sp, 2), (3, 1))
    ax7 = plt.subplot2grid((sp, 2), (0, 0),
                           rowspan=4)  # neuronal reconstruction
    #ax_empty1 = plt.subplot2grid((sp, 2), (4, 0))
    #ax_empty2 = plt.subplot2grid((sp, 2), (4, 1))
    #ax2 = fig.add_subplot(4,1,1) #(5,1,2)
    ax7.spines['right'].set_visible(False)
    ax7.spines['left'].set_visible(False)
    ax7.spines['top'].set_visible(False)
    ax7.spines['bottom'].set_visible(False)
    ax7.set_yticks([])
    ax7.set_xticks([])
    ax3.plot(recordings['time'], recordings['v_vect0'], color='maroon')
    ax3.set_xticks([])  # Use ax2's tick labels
    ax3.set_xlim([xlimbegin, xlimend])
    ax3.set_ylim([-90, 60])
    plt.yticks(fontsize=14)
    #ax3 = fig.add_subplot(4,1,2) #(5,1,3)
    ax4.plot(recordings['time'],
             recordings['v_vect142'],
             color='violet',
             lw=0.1)  # 142 instead of 161
    ax4.set_ylabel(' ')
    ax4.set_xticks([])  # Use ax2's tick labels
    ax4.set_xlim([xlimbegin, xlimend])  # ax4.set_xlim([xlimbegin,xlimend])
    ax4.set_ylim([-90, 60])
    plt.yticks(fontsize=14)
    #ax4 = fig.add_subplot(4,1,3) #(5,1,4)
    ax5.plot(recordings['time'], recordings['v_vect79'], color='orange')  # 161
    ax5.set_xticks([])  # Use ax2's tick labels
    ax5.set_xlim([xlimbegin, xlimend])
    ax5.set_ylim([-90, 60])
    plt.yticks(fontsize=14)
    #ax5 = fig.add_subplot(4,1,4) #(5,1,5)
    ax6_plot = ax6.plot(recordings['time'],
                        recordings['v_vect16'],
                        color='green')  # 16 instead of 18
    #ax3.set_ylabel('mV')
    ax6.set_xlabel('time (ms)', size=14)
    ax6.set_xlim([xlimbegin, xlimend])
    ax6.set_ylim([-90, 60])
    plt.xticks(fontsize=14)  #, rotation=90)
    plt.yticks(fontsize=14)
    #fig.tight_layout()
    #fig.subplots_adjust(hspace=0.1 ,left=0.115)
    #fig.savefig('/home/userlab/neuron/figures/subplots-temp.pdf') #spikes_L23_LBC_cNAC187_5_BC143ax2-b.CNG.swc.pdf')

    #plt.show()
    #print pos[0] # 79
    #print pos[161] # 156
    #print pos[79] # 78
    #print pos[18] # 14
    #print new_pos[134] # 142
    #print new_pos[12] # 16

    path = '/home/userlab/neuron/L23_LBC_cNAC187_5/morphology/BC143ax2.CNG.swc'
    f = open(path, 'r')  # Bipolar Tolias

    ll = []
    for line in f.readlines():
        if (line[0] != "#"):
            ll.append(line.strip().split())

    f.close()

    for i in range(len(ll)):
        ll[i].append(ll[int(ll[i][6]) - 1][2])  # add X cordinate of the father
        ll[i].append(ll[int(ll[i][6]) - 1][3])  # add Y cordinate of the father

    #fig, ax = plt.subplots(figsize=(6/prop(path),6)) # for Cauli Basket
    clr = ['yellow', 'green', 'blue', 'red', 'orangered']
    for i in range(len(ll)):
        if (int(ll[i][1]) > 1):
            ax7.plot([ll[i][3], ll[i][8]],
                     [-(float(ll[i][2])), -float(ll[i][7])],
                     c=clr[int(ll[i][1])],
                     lw=float(ll[i][5]) * 6)  # For Cauli Basket

    #ax7.plot(-309 ,462,'bo',markersize=8)
    #ax7.plot(330 ,280,'go',markersize=8)
    #ax7.plot(-170 ,-250,color='orange',marker='o',markersize=8)

    ax7.annotate('1',
                 xy=(-300, 462),
                 xytext=(-200, 490),
                 arrowprops=dict(facecolor='violet', shrink=0.01))
    ax7.annotate('2',
                 xy=(-180, -250),
                 xytext=(-280, -220),
                 arrowprops=dict(facecolor='orange', shrink=0.01))
    ax7.annotate('3',
                 xy=(330, 290),
                 xytext=(230, 350),
                 arrowprops=dict(facecolor='green', shrink=0.01))
    ax7.annotate('stimulus',
                 xy=(0, 0),
                 xytext=(-400, -100),
                 arrowprops=dict(facecolor='black', shrink=0.01),
                 size=14)
    ax7.annotate('0',
                 xy=(0, 0),
                 xytext=(100, -80),
                 arrowprops=dict(facecolor='maroon', shrink=0.01))

    #ax.axis('off')
    #############
    #fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(6.4,4.8)) # , figsize=(8,6)) # width , high    6.4,4.8
    #ax1 = plt.subplot2grid((sp, 2), (4, 0),rowspan=8)
    #ax2 = plt.subplot2grid((sp, 2), (4, 1),rowspan=8, sharey=ax1)
    aa = []
    #aaa = []
    num_spikes = []
    aa.append(array(stimuli[0]['stimulus']))
    #aaa.append(array(stimuli[0]['stimulus']))
    #print "stimuli length = " , len(array(stimuli[0]['stimulus']))
    #print "stimuli= " , array(stimuli[0]['stimulus'])
    #print "dtt " , neuron.h.dt
    j2 = [
        i for i in stimuli[0]['stimulus']
        if ((i >= (500 / neuron.h.dt)) & (i < (neuron.h.tstop / neuron.h.dt)))
    ]  # 2000 , 5200
    #print len(j2)
    #num_spikes.append(len(j2))
    for i in new_pos:  #range(num_axon_sec2):
        v_value = []
        for j in range(int(neuron.h.tstop / neuron.h.dt + 0)):  # 4001   801
            v_value.append(recordings["v_vect" +
                                      str(i)][j])  # v_value.append(v_vec[j])
        c = (diff(sign(diff(v_value))) < 0).nonzero()[0] + 1  # local max

        cc = []  # only local max above zero
        for k in range(len(c)):
            if v_value[c[k]] > 0:  # -60
                cc.append(c[k])

        v_max = [cc[0]]
        for iii in range(len(cc) - 1):
            if (cc[iii + 1] > cc[iii] + 40):  # discard close peaks
                v_max.append(cc[iii + 1])

        ###
        #cc = [c[0]]
        #for iii in range(len(c)-1):
            #if (c[iii+1] > c[iii]+40): # discard close peaks
            #if (v_value[c[iii+1]]>0):
            #cc.append(c[iii+1])
            #elif (v_value[c[iii]]>0):
            #cc.append(c[iii]) # cc.append(c[iii+1])

            ##if (i==78):
            ##  print "cc", cc
            ##  #print "v_value[cc]" , v_value[cc]

            ##print cc , i
            #v_max = [] # only local max above zero  OR 30 ??
            #for k in range(len(cc)):
            ##if (i==78):
            ##  print "v_value[cc[k]]" , v_value[cc[k]]
            #if v_value[cc[k]] > 0: # -60
            #v_max.append(cc[k])
        aa.append(array(v_max))
        #if (i==78):
        #  print "v_max", v_max

        j3 = [
            ii for ii in v_max if ((ii >= (500 / neuron.h.dt))
                                   & (ii < (neuron.h.tstop / neuron.h.dt)))
        ]  # 2000 , 5200
        #aaa.append(np.array(j3) - j3[0] + 500/neuron.h.dt) # alignment
        #print pos[i] , len(j3) , float(len(j3)) / len(j2)
        num_spikes.append(len(j3))

    const = [float(x) / len(j2) for x in num_spikes]
    #print "len const " ,len(const)
    #print "num axon sec " , num_axon_sec

    cll = [
        'maroon', 'green', 'orange', 'deepskyblue', 'violet', 'navy',
        'dimgray', 'silver'
    ]  #'black' , 'gray'] # green instead of yellow
    fr = [1, .8, 0.75, 0.66, 0.5, 0.375, 0.2, 0]
    M = np.zeros((len(const), len(fr)))
    for i in range(len(const)):
        for k in range(len(fr)):
            M[i][k] = abs(const[i] - fr[k])

    clr = []
    for i in range(len(const)):
        clr.append(np.argmin(M[i]))

    cl = ['z']  # choose color for the raster plot
    for i in new_pos:
        cl.append(cll[int(clr[int(pos[i])])])

    aa = np.multiply(aa, neuron.h.dt)  # for the alignment change to 'aaa'
    P = []
    for pp in cll:
        P.append(float(cl.count(pp)) / (len(cl) - 1))

    print "P=", P
    P = [y for y in P if y != 0]
    #print "P=" , P
    q = 2
    print "M2=", sum([n**q for n in P])**(1 / (1 - q))
    q = 0.9999
    print "M0.9999=", sum([n**q for n in P])**(1 / (1 - q))
    import math
    print "Entropy2=", math.exp(1)**-(sum([n * np.log(n) for n in P]))
    print "percentage of branches with interrupted", 1 - (
        float(cl.count('maroon')) / (len(cl) - 1))
    ax2 = raster(aa, cl)
    ax2.set_xlabel('time (ms)', size=14)
    ax2.set_xlim([1000, neuron.h.tstop])  # 50

    ax1 = plt.subplot2grid((sp, 2), (5, 0), rowspan=sp - 5, sharey=ax2)

    for i in range(num_axon_sec):  # plot the dendrogram (axogram)
        ax1.plot([y2[i] - tbl[i][1] - 0.3, y2[i]], [pos[i] + 1, pos[i] + 1],
                 color=cll[int(clr[int(pos[i])])],
                 linewidth=diam[i] * 3,
                 solid_capstyle='butt')  # *3
        #ax1.plot([y2[i]-tbl[i][1]-0.3,y2[i]],[pos[i]+1,pos[i]+1],color='b',linewidth=diam[i]*2, solid_capstyle='butt')
        if (i > 0):
            ax1.plot([y2[i] - tbl[i][1], y2[i] - tbl[i][1]],
                     [pos[i] + 1, pos[int(xy[i])] + 1],
                     color=cll[int(clr[int(pos[i])])],
                     linewidth=0.1,
                     solid_capstyle='butt')  # diam[i]*5)
            #ax1.plot([y2[i]-tbl[i][1] , y2[i]-tbl[i][1]] , [pos[i]+1,pos[int(xy[i])]+1],color='b',linewidth= 0.1, solid_capstyle='butt')

    ax1.set_yticks([])
    ax2.set_yticks([])
    ax1.set_xlabel('length ($\mu$m)', size=14)
    #ax1.set_ylim([-1,len(tbl)-0])  # ax1.set_ylim([-1,len(tbl)-0.8])  #  shared y axis
    ax1.set_xlim([0, max(y2)])  #math.ceil(max(y2)/100.0)*100])  #  +20
    ax1.set_ylim([-.5, 271.5])
    ax2.set_ylim([-.5, 271.5])
    ax1.spines['right'].set_visible(False)
    ax1.spines['left'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    #ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)

    ax1.text(-15, 79, '0', fontsize=10, ha='center',
             va='center')  # print '0' left to the main branch in axogram
    #ax1.text(y2[161]+50,156,'1', fontsize=10,ha='center',va='center')
    ax1.text(y2[142] + 15, 134, '1', fontsize=10, ha='center', va='center')
    ax1.text(y2[79] + 15, 78, '2', fontsize=10, ha='center', va='center')
    ax1.text(y2[16] + 15, 12, '3', fontsize=10, ha='center', va='center')
    #print y2[161] # 156
    #print y2[142]
    #print y2[79] # 78
    #print y2[18] # 14

    from matplotlib.font_manager import FontProperties
    font0 = FontProperties()
    font = font0.copy()
    font.set_weight('bold')

    ax1.text(-40, 500, 'a', fontsize=14, fontproperties=font)
    ax1.text(880, 500, 'b', fontsize=14, fontproperties=font)

    ax1.text(1900, 493, '0',
             fontsize=12)  # the number right to train plot (subplot B)
    ax1.text(1900, 446, '1', fontsize=12)
    ax1.text(1900, 401, '2', fontsize=12)
    ax1.text(1900, 355, '3', fontsize=12)

    ax1.text(-40, 280, 'c', fontsize=14, fontproperties=font)
    ax1.text(880, 280, 'd', fontsize=14, fontproperties=font)
    fig.text(0.46, 0.82, 'mV', va='center', rotation='vertical', size=14)
    fig.tight_layout()
    fig.subplots_adjust(hspace=0.1, wspace=0.15)  # ,left=0.115)
    #fig.subplots_adjust(wspace=0.1) #, bottom=0.09)
    fig.savefig('/home/userlab/BBP/NeuroMorpho/recons/bNAC_PIC23.pdf')
Example #51
0
def getFeatImg(rowHead, allInfo, fileFlag, show=False):
    labels = ['good', 'bad']
    good = []
    bad = []
    selectCol = int(fileFlag)
    selectColName = rowHead[0][selectCol]
    dataList = []
    datingLabels = []
    for one in allInfo:
        # #特殊处理,是语音文本,得到其长度
        # if selectCol == 1:
        #     tag = one[-1]
        #     tagType = type(tag)
        #     if tagType == types.String:
        #         if tag == 'good':
        #             # print selectCol, one[selectCol]
        #             good.append(len(one[selectCol]))
        #         elif tag == 'bad':
        #             bad.append(len(one[selectCol]))
        #     elif tagType == types.Integer:
        #         if tag == 1:
        #             # print selectCol, one[selectCol]
        #             good.append(len(one[selectCol]))
        #         elif tag == 0:
        #             bad.append(len(one[selectCol]))
        #     continue
        if one[selectCol] == '':
            continue
        tag = one[-1]
        if not tag.isnumeric():
            if tag == 'good':
                # print selectCol, one[selectCol]
                good.append(int(one[selectCol]))
            elif tag == 'bad':
                bad.append(int(one[selectCol]))
        else:
            tag = int(tag)
            if tag == 1:
                # print selectCol, one[selectCol]
                good.append(int(one[selectCol]))
            elif tag == 0:
                bad.append(int(one[selectCol]))

    #show picture
    # from numpy import *
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    font = FontProperties(
        fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf',
        size=14)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    dataMat = [mat([good]), mat([bad])]
    # plt.boxplot(dataMat, labels = labels, whis = 1.5)
    plt.boxplot(dataMat, labels=labels)

    title = 'audio_column_' + str(fileFlag) + '_' + selectColName
    ax.set_title(title, fontproperties=font)
    plt.xlabel('好坏', fontproperties=font)
    plt.ylabel(selectColName, fontproperties=font)
    plt.savefig("img/" + title + ".jpg")
    if show:
        plt.show()
Example #52
0

fig1 = plt.figure(figsize=(10,8))
ax1 = plt.axes(projection=wpsproj)

ax1.pcolormesh(dem_lons, dem_lats, dem, cmap='terrain', vmin=0, vmax=6560, alpha=1, transform=ccrs.PlateCarree())
ax1.coastlines('50m', linewidth=0.8)
ax1.add_feature(OCEAN, edgecolor='k')#, facecolor='deepskyblue')
ax1.add_feature(LAKES, edgecolor='k')#, facecolor='deepskyblue')

states = NaturalEarthFeature(category='cultural', scale='10m', facecolor='none',
                             name='admin_1_states_provinces_shp')
ax1.add_feature(states, linewidth=0.5)
ax1.add_feature(cfeature.BORDERS)

font0 = FontProperties()
font0.set_weight('bold')

# d01
corner_x1, corner_y1 = reproject_corners(corner_lon_full[0,:], corner_lat_full[0,:], wpsproj, latlonproj)
ax1.set_xlim([corner_x1[0]-length_x[0]/15, corner_x1[3]+length_x[0]/15])
ax1.set_ylim([corner_y1[0]-length_y[0]/15, corner_y1[3]+length_y[0]/15])

# d01 box
ax1.add_patch(mpl.patches.Rectangle((corner_x1[0], corner_y1[0]),  length_x[0], length_y[0], 
                                    fill=None, lw=3, edgecolor='white', zorder=10))
ax1.text(corner_x1[0]+length_x[0]*0.05, corner_y1[0]+length_y[0]*0.9, 'D01',
         fontproperties=font0, size=15, color='white', zorder=10)
# d02 box
corner_x2, corner_y2 = reproject_corners(corner_lon_full[1,:], corner_lat_full[1,:], wpsproj, latlonproj)
ax1.add_patch(mpl.patches.Rectangle((corner_x2[0], corner_y2[0]),  length_x[1], length_y[1], 
Example #53
0
plt.title("Image format conversion - YARN", fontsize=20)
plt.ylabel("Memory (GB)", fontsize=15)
plt.xlabel("Timestamp", fontsize=15)
#plt.xlim([datetime(2017, 02, 01, 14, 22, 00), datetime(2017, 02, 01, 14, 35, 00)])
plt.ylim([-5, 250])

#ax.xaxis.set_major_locator(mdates.SecondLocator(interval=60))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:S'))

ax.plot_date(
    time_stamp_list,
    total_memory_list,
    fmt="r-",
    label="total memory",
)
#ax.plot_date(time_stamp_list, total_free_memory_list, fmt="g-.", label="free memory", )
ax.plot_date(time_stamp_list,
             total_used_memory_list,
             fmt="b-*",
             label="used memory")

# font of the legend
fontP = FontProperties()
fontP.set_size('medium')

ax.legend(loc='upper right', shadow=False, ncol=3, prop=fontP)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
ax.grid(True)
fig.autofmt_xdate()
plt.show()
parameters = settings.parameters
lion_power_plot_data = exp_lion_power_performance.load_lion_power_performance(
    parameters=parameters)
idw_power_plot_data = exp_idw_power_performance.load_idw_power_performance(
    parameters=parameters)[-1]

baseline_precision = generate_data.load_baseline_precision(
    parameters=parameters)

# Accuracy-vs-power plot
legend_list = list()
f, ax = plt.subplots(dpi=300)
f.set_size_inches(3.3, 2)

font_properties = FontProperties()
font_properties.set_family('serif')
font_properties.set_name('Times New Roman')
font_properties.set_size(8)

power_perc_combos = lion_power_plot_data.keys()
all_percentages = sorted(set([int(i.split(';')[0])
                              for i in power_perc_combos]))
x = sorted(set([float(i.split(';')[1]) for i in power_perc_combos]))
color_dict = {90: 'blue', 95: 'green', 99: 'red', 100: 'cyan'}
legend_list = list()
legend_lines = list()
print(all_percentages)
for perc in all_percentages:
    y = list()
    for cur_power in x:
Example #55
0
from tkinter import *  # get widget classes
from tkinter.messagebox import *  # get standard dialogs
from tkinter.filedialog import askopenfilename  # get standard dialogs
from tkinter import ttk
from math import sqrt
import re

from osgeo import gdal, gdalconst, ogr
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname="font/msyh.ttc")
from matplotlib.figure import Figure
from matplotlib.colors import NoNorm
# from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.backend_tkagg import *
from matplotlib.backend_bases import key_press_handler


def notdone():
    showerror('Not implemented', 'Not yet available')


# 打开文件操作
def openrasterfile():
    global rfilename
    rfilename = askopenfilename()
    if rfilename:
        showinfo("openfile", "successfully loaded!!!")
the maintenance of early phase long-term potentiation".

This script requires that `read_roi`,`numpy`,`matplotlib` and `seaborn` are installed within 
the Python environment you are running this script in.
"""

import sys
sys.path.append('../')

import numpy as np
import matplotlib.pyplot as plt
from ampartrafficking.frap import FRAP
import seaborn as sns
sns.set_style("ticks")
from matplotlib.font_manager import FontProperties
fontLgd = FontProperties()
fontLgd.set_size('xx-small')
from read_roi import read_roi_zip
from scipy import stats
plt.rcParams['svg.fonttype'] = 'none'

#%%

roi = read_roi_zip('Data\\Tatavarty2013_FRAP_Fig3D_RoiSet.zip')

xAxis = 80 / (roi['xAxis']['x2'] - roi['xAxis']['x1'])
yAxis = 100 / (roi['yAxis']['y2'] - roi['yAxis']['y1'])
dataPoints_x = (
    (np.array(roi['dataPoints']['x']) - roi['yAxis']['x1']) * xAxis) - 1.5
dataPoints_y = ((np.array(roi['dataPoints']['y']) - roi['yAxis']['y1']) *
                yAxis)
Example #57
0
def getChineseFont():
    return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
# -*- coding: utf-8 -*-
from PIL import Image
from pylab import *

# 添加中文字体支持
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"/Users/zhangjianfeng/Library/Fonts/simhei.ttf",
                      size=14)
im = array(Image.open('../data/empire.jpg').convert('L'))  # 打开图像,并转成灰度图像

figure()
subplot(121)
gray()
contour(im, origin='image')
axis('equal')
axis('off')
title(u'图像轮廓', fontproperties=font)

subplot(122)
hist(im.flatten(), 128)
title(u'图像直方图', fontproperties=font)
plt.xlim([0, 260])
plt.ylim([0, 11000])

show()
Example #59
0
df = pd.DataFrame(columns=['饿了么', '美团外卖', '百度外卖'])
df['饿了么'] = [
    week1[0], week2[0], week3[0], week4[0], week5[0], week6[0], week7[0],
    week8[0]
]
df['美团外卖'] = [
    week1[1], week2[1], week3[1], week4[1], week5[1], week6[1], week7[1],
    week8[1]
]
df['百度外卖'] = [
    week1[2], week2[2], week3[2], week4[2], week5[2], week6[2], week7[2],
    week8[2]
]
print(df)
plt.figure(figsize=(8, 6))
zhfont1 = FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
plt.legend(prop=zhfont1)

# plt.plot(range(len(df["key"].values)),  df["count"].values)
plt.plot(range(8), df['饿了么'].values, marker='o', label='ele', color='b')
plt.plot(range(8), df['美团外卖'].values, marker='o', label="meitaun", color='y')
plt.plot(range(8), df['百度外卖'].values, marker='o', label="baidu", color='r')
# plt.plot(range(8),  df['百度外卖'].values,s=30,c='blue',marker='x',alpha=0.5,label='百度外卖')
# plt.xticks(range(len(df["key"].values)),df["key_name"].values) #给X轴赋值名称
# plt.xticks(range(len(df["key"].values)),df["key_name"].values)
plt.legend(loc='upper right')
plt.title(u"关键字搜索DCG评测", fontproperties=getChineseFont())
plt.xlabel(u"评测次数", fontproperties=getChineseFont())
plt.ylabel(u"评测分数", fontproperties=getChineseFont())
plt.show()
Example #60
0
import itertools as it
import os

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pylab
from matplotlib.font_manager import FontProperties

OPT_FONT_NAME = 'Helvetica'
TICK_FONT_SIZE = 20
LABEL_FONT_SIZE = 22
LEGEND_FONT_SIZE = 24
LABEL_FP = FontProperties(style='normal', size=LABEL_FONT_SIZE)
LEGEND_FP = FontProperties(style='normal', size=LEGEND_FONT_SIZE)
TICK_FP = FontProperties(style='normal', size=TICK_FONT_SIZE)

MARKERS = ([
    'o', 's', 'v', "^", "h", "v", ">", "x", "d", "<", "|", "", "+", "_"
])
# you may want to change the color map for different figures
COLOR_MAP = ('#F15854', '#5DA5DA', '#60BD68', '#B276B2', '#DECF3F', '#F17CB0',
             '#B2912F', '#FAA43A', '#AFAFAF')
# you may want to change the patterns for different figures
PATTERNS = ([
    "|", "\\", "/", "+", "-", ".", "*", "x", "o", "O", "////", ".", "|||", "o",
    "---", "+", "\\\\", "*"
])
LABEL_WEIGHT = 'bold'
LINE_COLORS = COLOR_MAP
LINE_WIDTH = 3.0