python类FontProperties()的实例源码

postprocessing_stance.py 文件源码 项目:seqhawkes 作者: mlukasik 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def display_results_figure(results, METRIC):
    import pylab as pb
    color = iter(pb.cm.rainbow(np.linspace(0, 1, len(results))))
    plots = []
    for method in results.keys():
        x = []
        y = []
        for train_perc in sorted(results[method].keys()):
            x.append(train_perc)
            y.append(results[method][train_perc][0])
        c = next(color)
        (pi, ) = pb.plot(x, y, color=c)
        plots.append(pi)
    from matplotlib.font_manager import FontProperties
    fontP = FontProperties()
    fontP.set_size('small')
    pb.legend(plots, map(method_name_mapper, results.keys()),
              prop=fontP, bbox_to_anchor=(0.6, .65))
    pb.xlabel('#Tweets from target rumour for training')
    pb.ylabel('Accuracy')
    pb.title(METRIC.__name__)
    pb.savefig('incrementing_training_size.png')
graphicsData.py 文件源码 项目:tieba-zhuaqu 作者: ankanch 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def pieGraphics(Labels,ValueList,graphicTitle='??'):
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"]
    maxdata = max(ValueList)
    explode = []
    for v in ValueList:
        if v == maxdata:
            explode.append(0.1)
        else:
            explode.append(0)
    print(explode)
    patches,l_text,p_text = plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%',explode=explode ,shadow=True, startangle=90)
    for font in l_text:
        font.set_fontproperties(FontProperties(fname=PATH_SUFFIX+'SIMLI.TTF'))
    plt.title(graphicTitle,fontproperties=font_set,y=1.05)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.show()
graphicsData.py 文件源码 项目:tieba-zhuaqu 作者: ankanch 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def pieGraphics(Labels,ValueList,graphicTitle='??'):
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"]
    maxdata = max(ValueList)
    explode = []
    for v in ValueList:
        if v == maxdata:
            explode.append(0.1)
        else:
            explode.append(0)
    print(explode)
    patches,l_text,p_text = plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%',explode=explode ,shadow=True, startangle=90)
    for font in l_text:
        font.set_fontproperties(FontProperties(fname=PATH_SUFFIX+'SIMLI.TTF'))
    plt.title(graphicTitle,fontproperties=font_set,y=1.05)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.show()
graphicsData.py 文件源码 项目:tieba-zhuaqu 作者: ankanch 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def pieGraphics(Labels,ValueList,graphicTitle='??'):
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"]
    maxdata = max(ValueList)
    explode = []
    for v in ValueList:
        if v == maxdata:
            explode.append(0.1)
        else:
            explode.append(0)
    print(explode)
    patches,l_text,p_text = plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%',explode=explode ,shadow=True, startangle=90)
    for font in l_text:
        font.set_fontproperties(FontProperties(fname=PATH_SUFFIX+'SIMLI.TTF'))
    plt.title(graphicTitle,fontproperties=font_set,y=1.05)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.show()
profile_plotter.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _initialize_instance(cls, obj, profiles, labels, plot_specs, y_log):
        from matplotlib.font_manager import FontProperties
        obj._font_properties = FontProperties(family='stixgeneral', size=18)
        obj._font_color = None
        obj.profiles = ensure_list(profiles)
        obj.x_log = None
        obj.y_log = {}
        if y_log is not None:
            for field, log in y_log.items():
                field, = obj.profiles[0].data_source._determine_fields([field])
                obj.y_log[field] = log
        obj.y_title = {}
        obj.label = sanitize_label(labels, len(obj.profiles))
        if plot_specs is None:
            plot_specs = [dict() for p in obj.profiles]
        obj.plot_spec = plot_specs
        obj.plots = PlotContainerDict()
        obj.figures = FigureContainer(obj.plots)
        obj.axes = AxesContainer(obj.plots)
        obj._setup_plots()
        return obj
plot_container.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, data_source, figure_size, fontsize):
        from matplotlib.font_manager import FontProperties
        self.data_source = data_source
        self.ds = data_source.ds
        self.ts = self._initialize_dataset(self.ds)
        if iterable(figure_size):
            self.figure_size = float(figure_size[0]), float(figure_size[1])
        else:
            self.figure_size = float(figure_size)
        font_path = matplotlib.get_data_path() + '/fonts/ttf/STIXGeneral.ttf'
        self._font_properties = FontProperties(size=fontsize, fname=font_path)
        self._font_color = None
        self._xlabel = None
        self._ylabel = None
        self._minorticks = {}
        self._field_transform = {}
mplcanvas.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def resizeEvent(self, event):
        w = event.size().width()
        h = event.size().height()
        # Leave a fixed amount for the axes
        padding = 7.5*FontProperties(size=rcParams['axes.labelsize']).get_size_in_points()
        posx = padding/w
        posy = padding/h
        self.axes.set_position([posx, posy, 0.97-posx, 0.97-posy])
        super(MplCanvas, self).resizeEvent(event)
finace_analyze.py 文件源码 项目:base_function 作者: Rockyzsu 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def personal_money():
    baidu_current = 2619
    baidu_fix = 50000
    jd = 19284
    lujinsuo = 43998
    icbc = 455
    cmb = 77
    zhifubao = 0
    stock_ht = 53200
    stock_gj = 19112
    fund = 3515
    qq = 1000
    X = [baidu_current + baidu_fix, jd, lujinsuo, icbc, cmb, stock_ht, stock_gj, fund, qq]
    labels = [u'??', u'??', u'???', u'??', u'??', u'??', u'??', u'??', u'QQ']
    plt.figure()
    plt.subplot(2, 1, 1)
    p = plt.pie(X,
                labels=labels,

                autopct='%1.1f'
                )
    print p
    # plt.show()
    print p[1]
    # ??????
    for font in p[1]:
        font.set_fontproperties(mpl.font_manager.FontProperties(
            fname='C:/Windows/winsxs/amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_6.1.7600.16385_none_e417159f3b4eb1b7/simfang.ttf'))

    plt.subplot(2, 1, 2)
    x2 = [baidu_fix + baidu_current + jd + lujinsuo + icbc + cmb + qq, fund + stock_gj + stock_ht]
    print x2
    labels2 = [u'??', u'??']
    p2 = plt.pie(x2, labels=labels2,autopct='%1.1f')

    for font2 in p2[1]:
        font2.set_fontproperties(mpl.font_manager.FontProperties(
            fname='C:/Windows/winsxs/amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_6.1.7600.16385_none_e417159f3b4eb1b7/simfang.ttf'))

    plt.show()
Utilities.py 文件源码 项目:Hive 作者: rwuilbercq 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def ConvergencePlot(cost):
    """

    Monitors convergence.

    Parameters:
    ----------

        :param dict cost: mean and best cost over cycles/generations as returned
                          by an optimiser.

    """

    font = FontProperties();
    font.set_size('larger');
    labels = ["Best Cost Function", "Mean Cost Function"]
    plt.figure(figsize=(12.5, 4));
    plt.plot(range(len(cost["best"])), cost["best"], label=labels[0]);
    plt.scatter(range(len(cost["mean"])), cost["mean"], color='red', label=labels[1]);
    plt.xlabel("Iteration #");
    plt.ylabel("Value [-]");
    plt.legend(loc="best", prop = font);
    plt.xlim([0,len(cost["mean"])]);
    plt.grid();
    plt.show();

# ---- END
plot_utils.py 文件源码 项目:smp_base 作者: x75 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def set_fontprops():
    fontP = FontProperties()
    fontP.set_size('small')
    return fontP
indicators.py 文件源码 项目:Machine_Learning_Trading_System 作者: historycapital 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_stoch_indicator(price,sma,stochk,file_name):

    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(211)
    ax.set(title = 'AAPL with Stochastic Indicator')
    ax.plot(price,label = 'AAPL Price')
    ax.plot(sma,label = 'SMA(21)')
    #ax.plot(upper_band, label = 'upper_band', color='r')
    #ax.plot(bottom_band,label = 'bottom_band',color='r')
    ax.set_ylabel('Price')
    #ax.set_ylim([0,2])
    #start, end = ax.get_xlim()
    #ax.xaxis.set_ticks(np.arange(start,end,90))
    L = plt.legend()
    L.get_texts()[0].set_text('AAPL Price')
    L.get_texts()[0].set_text('SMA(21)')
    #L.get_texts()[1].set_text('Upper_band')
    #L.get_texts()[2].set_text('Lower_band')
    ax.tick_params(labelbottom='off')
    ax.legend(loc = 'upper center',bbox_to_anchor = (0.55,1.0), prop = {'size':7})
    ###create font properties
    #fontP = FontProperties()
    #fontP.set_size('small')
    #plt.legend([ax], "title",prop = fontP)

    ax1 = fig.add_subplot(212)
    ax1.plot(stochk,label = 'stochk',color = 'r')
    #ax1.plot(stochd,label = 'stochd', color = 'green')
    ax1.set_ylabel('Stochastic Oscillator')
    ax1.set_xlabel('Date')
    ax1.axhline(20.0, color = 'black')
    ax1.axhline(80.0, color = 'black')
    #start1, end1 = ax1.get_xlim()
    #ax1.xaxis.set_ticks(np.arange(start,end,90))
    fig.subplots_adjust(hspace=0.05)#,left = 0.2, right = 1.0, top = 0.2, bottom = 0.1)
    plt.xticks(rotation=30)
    plt.savefig(file_name)
    #plt.show()
indicators.py 文件源码 项目:Machine_Learning_Trading_System 作者: historycapital 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def plot_bollinger_band_indicator(price,sma,upper_band, bottom_band,bbp, file_name):

    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(211)
    ax.set(title = 'AAPL with Bollinger Band Indicator')
    ax.plot(price,label = 'AAPL Price')
    ax.plot(sma,label = 'SMA(21)')
    ax.plot(upper_band, label = 'upper_band', color='r')
    ax.plot(bottom_band,label = 'bottom_band',color='r')
    ax.set_ylabel('Price')
    #ax.set_ylim([0,2])
    #start, end = ax.get_xlim()
    #ax.xaxis.set_ticks(np.arange(start,end,90))
    L = plt.legend()
    L.get_texts()[0].set_text('AAPL Price')
    L.get_texts()[1].set_text('SMA(21)')
    L.get_texts()[2].set_text('Upper_band')
    L.get_texts()[3].set_text('Lower_band')
    ax.tick_params(labelbottom='off')
    ax.legend(loc = 'upper center',bbox_to_anchor = (0.55,1.0), prop = {'size':7})
    ###create font properties
    #fontP = FontProperties()
    #fontP.set_size('small')
    #plt.legend([ax], "title",prop = fontP)

    ax1 = fig.add_subplot(212)
    ax1.plot(bbp,label = 'bbp',color = 'r')
    ax1.set_ylabel('Bollinger Band (%BB)')
    ax1.set_xlabel('Date')
    ax1.axhline(0.0, color = 'black')
    ax1.axhline(1.0, color = 'black')
    fig.subplots_adjust(hspace=0.1)
    #start, end = ax.get_xlim()
    #ax1.xaxis.set_ticks(np.arange(start,end,90))
    plt.xticks(rotation=30)
    plt.savefig(file_name)
    #plt.show()
indicators.py 文件源码 项目:Machine_Learning_Trading_System 作者: historycapital 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def plot_rsi_indicator(price,sma,rsi, file_name):

    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(211)
    ax.set(title = 'AAPL with RSI Indicator')
    ax.plot(price,label = 'AAPL Price')
    ax.plot(sma,label = 'SMA(21)')
    #ax.plot(upper_band, label = 'upper_band', color='r')
    #ax.plot(bottom_band,label = 'bottom_band',color='r')
    ax.set_ylabel('Price')
    #ax.set_ylim([0,2])
    #start, end = ax.get_xlim()
    #ax.xaxis.set_ticks(np.arange(start,end,90))
    L = plt.legend()
    L.get_texts()[0].set_text('AAPL Price')
    L.get_texts()[1].set_text('SMA(21)')
    #L.get_texts()[1].set_text('Upper_band')
    #L.get_texts()[2].set_text('Lower_band')
    ax.tick_params(labelbottom='off')
    ax.legend(loc = 'upper center',bbox_to_anchor = (0.55,1.0), prop = {'size':7})
    ###create font properties
    #fontP = FontProperties()
    #fontP.set_size('small')
    #plt.legend([ax], "title",prop = fontP)

    ax1 = fig.add_subplot(212)
    ax1.plot(rsi,label = 'rsi',color = 'r')
    ax1.set_ylabel('Relative Strength Index')
    ax1.set_xlabel('Date')
    ax1.axhline(30.0, color = 'black')
    ax1.axhline(70.0, color = 'black')
    #start1, end1 = ax1.get_xlim()
    #ax1.xaxis.set_ticks(np.arange(start,end,90))
    fig.subplots_adjust(hspace=0.1)
    plt.xticks(rotation=30)
    plt.savefig(file_name)
    #plt.show()
cute_plot.py 文件源码 项目:cellcomplex 作者: VirtualPlants 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def surface_plot(figure,X,Y,Z,color1,color2=None,xlabel="",ylabel="",zlabel="",alpha=1.0,linewidth=3,label=""):
    from mpl_toolkits.mplot3d import axes3d
    from matplotlib.colors import LinearSegmentedColormap

    if color2 is None:
        color2 = color1

    cdict = {'red':   ((0.0, color1[0], color1[0]),(1.0, color2[0], color2[0])),
             'green': ((0.0, color1[1], color1[1]),(1.0, color2[1], color2[1])),
             'blue':  ((0.0, color1[2], color1[2]),(1.0, color2[2], color2[2]))}

    cmap = LinearSegmentedColormap('CMap', cdict)


    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111,projection='3d')

    if X.ndim<2:
        X = np.tile(np.array(X),(Y.shape[-1],1)).transpose()
    if Y.ndim<2:
        Y = np.tile(np.array(Y),(X.shape[0],1))

    axes.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cmap,alpha=alpha,linewidth=linewidth,label=label)

    axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
    axes.set_xlim(X.min(),X.max())
    axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
    axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
    axes.set_ylim(Y.min(),Y.max())
    axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
    axes.set_zlabel(zlabel, fontproperties=font, size=10, style='italic')
    axes.set_zlim(Z.min(),Z.max())
    axes.set_zticklabels(axes.get_zticks(),fontproperties=font, size=12)
cute_plot.py 文件源码 项目:cellcomplex 作者: VirtualPlants 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def density_plot(figure,X,Y,color,xlabel="",ylabel="",n_points=10,linewidth=1,marker_size=40.,alpha=1.0,label=""):
    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111)
    # axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.2)
    # ratios = (Y-Y.min())/(Y.max()-Y.min())
    # X_min = X.mean()-3*X.std()
    # X_max = X.mean()+3*X.std()
    X_min = np.percentile(X,100/n_points)
    X_max = np.percentile(X,100 - 100/n_points)
    Y_min = np.percentile(Y,100/n_points)
    # Y_min = Y.mean()-3*Y.std()
    Y_max = np.percentile(Y,100 - 100/n_points)

    X_grid = np.linspace(X_min,X_max,n_points)
    Y_grid = np.linspace(Y_min,Y_max,n_points)

    X_sampled = X_grid[vq(X,X_grid)[0]]
    Y_sampled = Y_grid[vq(Y,Y_grid)[0]]

    point_density = {}
    for x in np.unique(X_sampled):
        point_count = nd.sum(np.ones_like(np.where(X_sampled==x)),Y_sampled[np.where(X_sampled==x)],index=np.unique(Y_sampled))
        for i,y in enumerate(np.unique(Y_sampled)):
            point_density[(x,y)] = point_count[i]/len(Y)

    point_area = np.array([np.pi*10.0*marker_size*point_density[(x,y)]/np.array(point_density.values()).max() for x,y in zip(X_sampled,Y_sampled)])
    #colors = np.random.rand(len(X))
    colors = np.array([point_density[(x,y)]/np.array(point_density.values()).max() * color for x,y in zip(X_sampled,Y_sampled)])
    colors += np.array([(1-point_density[(x,y)]/np.array(point_density.values()).max()) * np.ones(3) for x,y in zip(X_sampled,Y_sampled)])

    axes.scatter(X_sampled,Y_sampled,s=point_area,c=colors,linewidth=linewidth,alpha=alpha,label=label)
    axes.set_xlim(X_min,X_max)
    axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
    axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
    axes.set_ylim(Y_min,Y_max)
    axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
    axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
cute_plot.py 文件源码 项目:cellcomplex 作者: VirtualPlants 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def smooth_plot(figure,X,Y,color1,color2,xlabel="",ylabel="",filled=False,n_points=400,smooth_factor=1.0,spline_order=3,linewidth=3,alpha=1.0,label=""):
    """
    """
    X_smooth = np.linspace(X.min(),X.max(),n_points)
    tck = splrep(X,Y,s=smooth_factor,k=spline_order)
    Y_smooth = splev(X_smooth,tck,der=0)

    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111)
    axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.2)
    if filled:
        axes.fill_between(X_smooth,Y_smooth,0,color=color2,alpha=0.1)
    for i in xrange(100):
        color = tuple(color1*(1.0-i/100.0) + color2*(i/100.0))
        if i == 0:
            axes.plot(X_smooth[(i*n_points/100):((i+1)*n_points)/100+1],Y_smooth[(i*n_points/100):((i+1)*n_points)/100+1],linewidth=linewidth,color=color,alpha=alpha,label=label)
        else:
            axes.plot(X_smooth[(i*n_points/100):((i+1)*n_points)/100+1],Y_smooth[(i*n_points/100):((i+1)*n_points)/100+1],linewidth=linewidth,color=color,alpha=alpha)
    axes.set_xlim(X.min(),X.max())
    axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
    axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
    if '%' in ylabel:
        axes.set_ylim(0,np.minimum(2*Y.max(),100))
    axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
    axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
cute_plot.py 文件源码 项目:cellcomplex 作者: VirtualPlants 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def violin_plot(figure,X,data,colors,xlabel="",ylabel="",n_points=400,violin_width=None,linewidth=3,marker_size=20):
    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111)
    if violin_width is None:
        if len(X)>1:
            violin_width = ((np.array(X)[1:] - np.array(X)[:-1]).mean())/3.
        else:
            violin_width = 0.33
    for x in xrange(len(X)):
        color = colors[x]

        Y = gaussian_kde(data[x])
        D_smooth = np.linspace(np.percentile(Y.dataset,1),np.percentile(Y.dataset,99),n_points)
        Y_smooth = Y.evaluate(D_smooth)
        Y_smooth = violin_width*Y_smooth/Y_smooth.max()
        axes.fill_betweenx(D_smooth,X[x],X[x]+Y_smooth,facecolor=color,alpha=0.1)
        axes.fill_betweenx(D_smooth,X[x],X[x]-Y_smooth,facecolor=color,alpha=0.1)
        axes.plot(X[x]+Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8)
        axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8)
        axes.plot([X[x]-Y_smooth[0],X[x]+Y_smooth[0]],[D_smooth[0],D_smooth[0]],color=color,linewidth=linewidth,alpha=0.8)
        axes.plot([X[x]-Y_smooth[-1],X[x]+Y_smooth[-1]],[D_smooth[-1],D_smooth[-1]],color=color,linewidth=linewidth,alpha=0.8)
        axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8)
        axes.plot(X[x],np.percentile(data[x],50),'o',markersize=marker_size,markeredgewidth=linewidth,color=color)
        axes.plot([X[x],X[x]],[np.percentile(data[x],25),np.percentile(data[x],75)],color=color,linewidth=2*linewidth,alpha=0.5)
    axes.set_xlim(min(X)-1,max(X)+1)
    axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
    axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
    axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
    axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
cute_plot.py 文件源码 项目:cellcomplex 作者: VirtualPlants 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def box_plot(figure,X,data,colors,xlabel="",ylabel="",box_width=None,linewidth=3,marker_size=20,alpha=1):
    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111)

    if box_width is None:
        if len(X)>1:
            box_width = ((np.array(X)[1:] - np.array(X)[:-1]).mean())/3.
        else:
            box_width = 0.33
    for x in xrange(len(X)):
        color = colors[x]
        box_color = np.array(color)/2.

        axes.fill_between([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],75),np.percentile(data[x],75)],[np.percentile(data[x],25),np.percentile(data[x],25)],facecolor=color,alpha=alpha/2.)
        axes.plot([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],50),np.percentile(data[x],50)],color=box_color,linewidth=linewidth,alpha=(alpha+1)/2)
        axes.plot([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],25),np.percentile(data[x],25)],color=box_color,linewidth=linewidth/2.,alpha=alpha)
        axes.plot([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],75),np.percentile(data[x],75)],color=box_color,linewidth=linewidth/2.,alpha=alpha)
        axes.plot([X[x]-box_width,X[x]-box_width],[np.percentile(data[x],25),np.percentile(data[x],75)],color=box_color,linewidth=linewidth/2.,alpha=alpha)
        axes.plot([X[x]+box_width,X[x]+box_width],[np.percentile(data[x],25),np.percentile(data[x],75)],color=box_color,linewidth=linewidth/2.,alpha=alpha)
        axes.plot([X[x],X[x]],[np.percentile(data[x],25),np.percentile(data[x],10)],color=box_color,linewidth=linewidth/3.,alpha=alpha)
        axes.plot([X[x],X[x]],[np.percentile(data[x],75),np.percentile(data[x],90)],color=box_color,linewidth=linewidth/3.,alpha=alpha)
        axes.plot([X[x]-box_width/4.,X[x]+box_width/5.],[np.percentile(data[x],10),np.percentile(data[x],10)],color=box_color,linewidth=linewidth/2.,alpha=alpha)
        axes.plot([X[x]-box_width/4.,X[x]+box_width/5.],[np.percentile(data[x],90),np.percentile(data[x],90)],color=box_color,linewidth=linewidth/2.,alpha=alpha)
        # axes.plot(X[x],np.percentile(data[x],50),'o',markersize=np.pi*np.power(box_width/2.,2.),markeredgewidth=linewidth/2.,color=color)

        outliers = [d for d in data[x] if (d < np.percentile(data[x],10)) or (d > np.percentile(data[x],90))]
        x_outliers = [X[x] for d in outliers]
        axes.scatter(x_outliers, outliers, s=marker_size/3.,c=color,linewidth=0,alpha=alpha/2.)

    axes.set_xlim(min(X)-1,max(X)+1)
    axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
    axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
    axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
    axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
browserHelpers.py 文件源码 项目:gcMapExplorer 作者: rjdkmr 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def init_font_matplotlib_qt(self):
        ''' Initialize font name list QFontComboBox.
        Also adds font from matplotlib default fonts
        '''
        # Font database of qt
        self.qtFontDatabase = QFontDatabase()

        # Getting path of matplotlib ttf directory
        mplDataPath = mpl.rcParams['datapath']
        mplFontPath = os.path.join(mplDataPath, 'fonts')
        mplTtfFontPath = os.path.join(mplFontPath, 'ttf')

        # Building ttf files list
        mplTtfList = []
        for f in os.listdir(mplTtfFontPath):
            if f.endswith('.ttf'):
                mplTtfList.append(os.path.join(mplTtfFontPath, f))

        # Getting name of each font from ttf files
        mplFontNameList = [mplFontManager.FontProperties(fname=fname).get_name() for fname in mplTtfList]

        # Getting name of each font from qt font database
        qtFontNameListQtype = self.qtFontDatabase.families()
        qtFontNameList =  [ str(qtFont) for qtFont in qtFontNameListQtype ]

        # Comparing and adding matplotlib font to qt font database
        for i in range(len(mplFontNameList)):
            matched = False
            for qtFont in qtFontNameList:
                if str(qtFont) == mplFontNameList[i]:
                    matched = True

            if not matched:
                self.qtFontDatabase.addApplicationFont(mplTtfList[i])
browserHelpers.py 文件源码 项目:gcMapExplorer 作者: rjdkmr 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def is_font_exist_in_mpl(self, fontname):
        result = None
        result = mplFontManager.findfont(mplFontManager.FontProperties(family=fontname))

        if mplFontManager.FontProperties(fname=result).get_name() == fontname:
            return True
        else:
            return False
MicapsFile.py 文件源码 项目:MicapsDataDraw 作者: flashlxy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def DrawTitle(m, title, headtxt):
        if m is plt:
            if title.mtitleposition is None:
                for desc in title.descs:
                    fontfile = r"C:\WINDOWS\Fonts\{0}".format(desc.font['family'])
                    if not os.path.exists(fontfile):
                        font = FontProperties(size=desc.font['fontsize'], weight=desc.font['weight'])
                    else:
                        font = FontProperties(fname=fontfile, size=desc.font['fontsize'], weight=desc.font['weight'])
                    plt.text(desc.pos[0], desc.pos[1], desc.text,
                             # size=desc.font['fontsize'], weight=desc.font['weight'],
                             color=desc.font['color'],
                             fontdict=desc.font,
                             fontproperties=font,
                             rotation=0,
                             ha='left', va='top')
            else:
                if title.mtitleposition == [0, 0]:
                    plt.title(headtxt, fontdict={'fontsize': 14})
                else:
                    plt.text(title.mtitleposition[0], title.mtitleposition[1], headtxt,
                             size=14,
                             weight='bold',
                             # color='blue',
                             # fontdict=desc.font,
                             # fontproperties=font,
                             rotation=0,
                             ha='left', va='top')
        else:
            plt.title(headtxt)
Map.py 文件源码 项目:MicapsDataDraw 作者: flashlxy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def GetFontProperties(font):
        fontfile = r"C:\WINDOWS\Fonts\{0}".format(font['family'])
        if not os.path.exists(fontfile):
            fp = FontProperties(family=font['family'], weight=font['weight'], size=font['size'])
        else:
            fp = FontProperties(fname=fontfile, weight=font['weight'], size=font['size'])
        return fp
Display.py 文件源码 项目:PyCS 作者: COSMOGRAIL 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def Display(curvelist):
    """
    Take a list of curve and plot it according to its type
    @type   curvelist:  list of curve
    @param  curvelist:  list of curve    for plotting

    @todo: improve the display with legend, color...
    """

    plt.figure(figsize=(12,8))  # sets figure size
    axes = plt.gca()
    # Something for astronomers only : we invert the y axis direction !
    axes.set_ylim(axes.get_ylim()[::-1])
    # Astronomers like minor tick marks :
    minorxLocator = MultipleLocator(100)

    for curve in curvelist:
        if curve.type=="purelightcurve":
            plt.plot(linspace(0,curve.length,curve.length*curve.res),curve.data)    

        if curve.type=="simlightcurve":
            if curve.name=="A": plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.originalcurve.data+curve.dmag,color="black",label="Original curve") 
            plt.errorbar(curve.datatime,curve.datamagoff(),curve.dataerr,ls='None',marker='.',ecolor="#BBBBBB", color=curve.plotcolor,label=str(curve.name)+str(curve.shift))
            plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.mlcurve.data+curve.dmag,color=curve.plotcolor)#,label="microlensing for "+str(curve.name))  
        plt.xlabel('time [j]')
        plt.ylabel('Magnitude ')
        plt.legend( numpoints = 1, prop = fm.FontProperties(size = 10))
    plt.show()
visualize_models.py 文件源码 项目:chainercv 作者: chainer 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 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()
ui.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def getFont():
    return fm.FontProperties(fname="c:/windows/fonts/simsun.ttc")
########################################################################
ui.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def DrawTs(pl, ts=[], lines = None, title="", high=[], low=[],mid=[], save_file=False,legends=None):
    """?????, ts: closes, save_file: ?????????"""
    pl.figure
    legend = []
    if len(ts)>0:
        pl.plot(ts)
        legend.append('ts')
    if len(high)>0:
        pl.plot(high)
        legend.append('high')
    if len(low)>0:
        pl.plot(low)
        legend.append('low')
    if len(mid)>0:
        pl.plot(mid)
        legend.append('mid')

    prop = fm.FontProperties(fname="c:/windows/fonts/simsun.ttc")
    if title != "":
        pl.title(title, fontproperties=prop)
    if lines != None:
        i = lines
        if i>=len(ts):
            i = len(ts)-1
        pl.plot([i,i], [ts[i]-ts[i]*0.1, ts[i]+ts[i]*0.1], 'g')
        legend.append('lines')
    if legends is not None:
        legend = legends
    pl.legend(legend, loc='upper left')
    if save_file:
        fname = 't3.png'
        pl.savefig(fname)
        return fname
    pl.show()
    pl.close()
ui.py 文件源码 项目:autoxd 作者: nessessary 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def DrawScatt(pl, x,y, title=''):
    pl.figure
    prop = fm.FontProperties(fname="c:/windows/fonts/simsun.ttc")
    if title != "":
        pl.title(title, fontproperties=prop)
    pl.scatter(x,y)
    pl.ylabel(u"???", fontproperties=prop)
    pl.xlabel(u"????(?)", fontproperties=prop)
    pl.show()
    pl.close()
ActivityInfo.py 文件源码 项目:WechatForwardBot 作者: grapeot 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, fontPath):
        if not os.path.exists(self.imgDir):
            os.mkdir(self.imgDir)
        self.client = client
        self.coll = self.client[dbName][collName]
        self.prop = FontProperties(fname=fontPath)
        logging.info('ActivityInfo initialized.')
visualization.py 文件源码 项目:DLDisambiguation 作者: Labyrinth108 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def getChineseFont():
    return FontProperties(fname='/Users/luoyi/Downloads/msyh.ttf')
create_kanji_dataset.py 文件源码 项目:MachineLearning 作者: timomernick 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def rasterize_kanji(kanji, weight, output_file):
    kanji = kanji[0:4] # strip extra stuff like footnotes off kanji

    prop = fm.FontProperties(fname="ipam.ttc", size=70)

    plt.figure(figsize=(1, 1))
    plt.text(0, 0, kanji, ha='center', va='center', fontproperties=prop)
    plt.xlim(-0.4, 0.1)
    plt.ylim(-0.1, 0.1)
    plt.axis("off")

    #plt.savefig(output_file)
    #image = scipy.misc.imread(output_file, flatten=True)

    buf = io.BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)
    image = PIL.Image.open(buf).convert(mode="L")
    buf.close()
    image = np.asarray(image, dtype=np.uint8)
    plt.close()

    image = scipy.misc.imresize(image, [kanji_height, kanji_width])
    image = skimage.img_as_float(image).astype(np.float32)

    image = 1.0 - image # make the background black and the text white

    if (weight == "bold"):
        erosion_size = 5
    elif (weight == "normal"):
        erosion_size = 3
    else:
        erosion_size = 0

    if (erosion_size > 0):
        kernel = np.ones((erosion_size, erosion_size), np.float32)
        image = cv2.dilate(image, kernel, iterations=1)
        scipy.misc.imsave(output_file, (1.0 - image))

    return image


问题


面经


文章

微信
公众号

扫码关注公众号