Пример #1
0
def SignalToNoise(D,fortalk=False):
    if fortalk:
        plt.figure()
    else:
        plt.subplot(211)
    time_of_emergence_figure(D,noisestart=cmip5.start_time(D.ALL.obs))
    
    plt.title("(a): Time of emergence for PDSI signal") 
    plt.xlim(1985,2050)
    plt.legend(ncol=2)
    if fortalk:

        plt.figure()
        ax=plt.subplot(111)
    else:
        ax=plt.subplot(212)
    start_time = cdtime.comptime(1981,1,1)
    ALL_SM = soil.SoilMoisture(D.ALL.obs.mask[0])
    ALL_SM.time_of_emergence(start_time,"30cm",ax=ax,color=cm.Set1(1/2.))
    ALL_SM.time_of_emergence(start_time,"2m",ax=ax,color=cm.Set1(2/2.))
    plt.xlim(1985,2050)
    plt.title("(b): Times of emergence for soil moisture metrics")
    #noisefigure(D)
    plt.legend()
    plt.title("(b): Preindustrial \"noise\" terms")
Пример #2
0
 def overview(self, dims=(0, 1)):
     reso = 50
     temp_X = np.vstack(
         map(
             np.ravel,
             np.meshgrid(np.linspace(-1, 1, reso), np.linspace(-1, 1,
                                                               reso)))).T
     test_X = np.zeros((temp_X.shape[0], 4))
     for i, d in enumerate(dims):
         test_X[:, d] = temp_X[:, i]
     test_Y = self.gp.predict(test_X)
     fig = plt.figure()
     ax = plt.subplot(111, projection="3d")
     for k in range(self.gp.y_train_.shape[1]):
         ax.plot(self.gp.X_train_[:, 0],
                 self.gp.X_train_[:, 1],
                 self.gp.y_train_[:, k],
                 "o",
                 color=cm.Set1(k))
         ax.plot_surface(test_X[:, 0].reshape(reso, reso),
                         test_X[:, 1].reshape(reso, reso),
                         test_Y[:, k].reshape(reso, reso),
                         color=cm.Set1(k),
                         alpha=0.3)
     plt.show(block=True)
     return fig
Пример #3
0
def plot_overlap(dm, origin, indices1, merlot_branches):
    fig, ax = plt.subplots(ncols=3, nrows=2)
    fig.set_size_inches(w=12, h=6)
    
    # plot the data 
    ax[0][0].scatter(dm[origin=="original", 3], dm[origin=="original", 4], c=cm.Set1(merlot_branches-1))
    ax[0][0].set_title("original data")
    ax[0][1].scatter(dm[origin=="simulated", 3], dm[origin=="simulated", 4], c=cm.Set1(indices1))
    ax[0][1].set_title("simulated data")
    ax[0][2].axis('off')
    
    progenitor = mpatches.Patch(color=cm.Set1(0), label='progenitor')
    nonskeletal = mpatches.Patch(color=cm.Set1(1), label='non-skeletal')
    intermediate = mpatches.Patch(color=cm.Set1(2), label='intermediate')
    cartilage = mpatches.Patch(color=cm.Set1(3), label='cartilage')
    bone = mpatches.Patch(color=cm.Set1(4), label='bone')
    branch_legend = [progenitor, nonskeletal, intermediate, cartilage, bone]
    ax[0][2].legend(loc=6, prop={'size': 10}, markerscale=2, handles=branch_legend)
    
    ax[1][0].scatter(dm[origin=="original", 3], dm[origin=="original", 4], label="original", alpha=0.05)
    ax[1][0].scatter(dm[origin=="simulated", 3], dm[origin=="simulated", 4], label="simulated", alpha=0.02)
    ax[1][0].set_title("original/simulated together")
    
    ax[1][1].axis('off')
    
    original = mpatches.Patch(color=cm.Set1(1), label='original')
    simulated = mpatches.Patch(color=cm.Set1(4), label='simulated')
    mix_legend = [original, simulated]
    ax[1][1].legend(loc=6, prop={'size': 10}, markerscale=2, handles=mix_legend)
    
    ax[1][2].axis('off')
Пример #4
0
def plot_roc_auc_profile(dm_df,
                         dmz,
                         accs,
                         num_solvers,
                         title=None,
                         plot_legend=False):
    colors = [
        cm.Set1(0) if x.find('gpc') != -1 else
        (cm.Set1(1) if x.find('xgb') != -1 else
         (cm.Set1(2) if x.find('logit') != -1 else cm.Greys(0.5)))
        for x in dm_df.columns
    ]
    linestyles = [
        '--' if x.find('stacking') != -1 else
        ('-.' if x.find('oncatenation') != -1 else
         ('-' if x.find('major_vote') != -1 else ':')) for x in dm_df.columns
    ]

    plt.figure(figsize=(5, 5))
    for cnt_solver in range(num_solvers):
        if dm_df.columns[cnt_solver].find('ss_mf_gpc') == -1 and dm_df.columns[
                cnt_solver].find('hetmogp') == -1:
            plt.plot(accs,
                     dmz[cnt_solver],
                     label=dm_df.columns[cnt_solver],
                     color=colors[cnt_solver],
                     linestyle=linestyles[cnt_solver])
    if 'ss_mf_gpc:multi-fidelity' in dm_df.columns:
        cnt_solver = dm_df.columns.tolist().index('ss_mf_gpc:multi-fidelity')
        plt.plot(accs,
                 dmz[cnt_solver],
                 label=dm_df.columns[cnt_solver],
                 color='k')
    if 'hetmogp:multi-fidelity' in dm_df.columns:
        cnt_solver = dm_df.columns.tolist().index('hetmogp:multi-fidelity')
        plt.plot(accs,
                 dmz[cnt_solver],
                 label=dm_df.columns[cnt_solver],
                 color='orange')
    if 'GPMA' in dm_df.columns:
        cnt_solver = dm_df.columns.tolist().index('GPMA')
        plt.plot(accs,
                 dmz[cnt_solver],
                 label=dm_df.columns[cnt_solver],
                 color='magenta')
    plt.xlim([0.4, 1])
    if plot_legend:
        plt.legend(loc=2, bbox_to_anchor=(1, 1))
    if title is not None:
        plt.title(title)
Пример #5
0
 def tsneplot(self, params):
     a = self.rel_data(params)
     if a == '  ':
         return plt.figure()
     if len(self.rdata) > self.maxfilenum:
         return plt.figure()
     sep = self.sep
     #calculate t-sne
     ts = TSNE(n_components=2)
     tscore = ts.fit_transform(self.rdata)
     #plot results
     f = plt.figure()
     r = 0.065, 0.125, 0.75, 0.75
     ax = f.add_axes(r)
     col = params['get_relevant']
     #plot labels in diffrent colors
     col = [int(x) for x in col]
     rleg = self.rll
     l = len(self.rll)
     cs = cm.Set1(np.arange(l) / (l + 0.001))
     for i in range(l):
         lab = rleg[i]
         lableg = [str(llab) for llab in lab]
         ax.plot(tscore[self.rdic[lab], 0],
                 tscore[self.rdic[lab], 1],
                 'o',
                 ms=3.0,
                 color=cs[i],
                 label=str(lableg)[1:-1].replace("'", ""))
     handles, labelss = ax.get_legend_handles_labels()
     ax.legend(handles=handles,
               loc='center left',
               bbox_to_anchor=(1, 0.5),
               numpoints=1)
     return f
Пример #6
0
def plot_sprint_pie(dictData, titlep):
    fig, ax = plt.subplots(2, 1)
    cs = cm.Set1(np.arange(len(dictData)) / len(dictData))
    data = sorted(dictData.items(), key=lambda x: x[1], reverse=True)
    labels = [x[0] for x in data]
    values = [x[1] for x in data]
    total = sum(values)
    cells = []
    for i, l in enumerate(labels):
        cells.append([
            str(values[i]) + " h",
            str(round(values[i] / total * 100.0)) + " %"
        ])
    ret = ax[0].pie(values, startangle=90, colors=cs)
    #ax[0].title(titlep);
    #legend = ax[0].legend(newlabels,bbox_to_anchor=(2.2, 0.5), loc=5, borderaxespad=0.)
    ax[0].axis("equal")
    ax[0].axis(aspect=2)
    ax[1].axis("off")
    rowlabels = labels
    ax[1].table(cellText=cells,
                bbox=[0.25, 0, 0.75, 1],
                cellLoc='center',
                rowLabels=rowlabels,
                rowColours=cs,
                colWidths=[.2] * 2)
    fig.show()
Пример #7
0
def total_car_pie_chart():
    figure(1, figsize=(8, 8))
    ax = axes([0.1, 0.1, 0.8, 0.8])
    labels = 'Mae Hong Son', 'Samut Songkram', 'Ranong', 'Bueng Kan', 'Amnat Charoen', 'Pang Nga', 'Nakhon Nayok', 'Trad', 'Satun', 'Sing Buri', 'Pathum Thani', 'Samut Prakarn', 'Ang Thong', 'Nong Bua Lamphu', 'Mukdahan', 'Chai Nat', 'Uthai Thani', 'Nonthaburi', 'Yasothon', 'Nakhon Phanom', 'Pattani', 'Tak', 'Nong Khai', 'Sra Kaew', 'Nan', 'Samut Sakorn', 'Narathiwat', 'Krabi', 'Phatthalung', 'Phrae', 'Uttaradit', 'Prachin Buri', 'Loei', 'Phayao', 'Yala', 'Lamphun', 'Kalasin', 'Chumphon', 'Phichit', 'Sukhothai', 'Petchaburi', 'Prachuap Kiri Khan', 'Maha Sarakham', 'Kamphaeng Phet', 'Trang', 'Chaiyaphum', 'Chanthaburi', 'Chachoengsao', 'Roi Et', 'Si Sa Ket', 'Khanchanaburi', 'Lop Buri', 'Ayuthaya', 'Saraburi', 'Phetchabun', 'Surin', 'Lampang', 'Phuket', 'Sakon Nakhon', 'Nakhon Pathom', 'Phitsanulok', 'Suphan Buri', 'Buri Rum', 'Ratchaburi', 'Nakhon Sawan', 'Surat Thani', 'Nakhon Si Thammarat', 'Udon Thani', 'Rayong', 'Chiang Rai', 'Ubon Ratchathani', 'Songkhla', 'Khon Kaen', 'Nakhon Ratchasima', 'Chiang Mai', 'Chonburi'
    fracs = [
        57536, 69583, 84644, 98111, 121165, 122745, 123291, 131348, 133028,
        135628, 144507, 144614, 150409, 154225, 155442, 172429, 177562, 182045,
        203899, 213657, 220058, 221147, 221173, 221598, 225384, 230365, 232610,
        245571, 246757, 253485, 255755, 257792, 259646, 264432, 266119, 269853,
        285970, 288511, 288931, 304531, 315275, 323393, 323476, 353195, 354028,
        360326, 362162, 378693, 387544, 387703, 397001, 412002, 416328, 416705,
        443819, 444978, 446759, 452411, 456473, 462914, 480971, 481576, 485829,
        492523, 554211, 597171, 617511, 645826, 685357, 700936, 701817, 814208,
        820245, 1293523, 1349910, 1432816
    ]
    cs = cm.Set1(np.arange(40) / 40.)
    explode = []
    for i in range(len(labels)):
        explode.append(1.8)
    pie(fracs,
        labels=labels,
        autopct='%1.2f%%',
        shadow=False,
        explode=explode,
        startangle=180,
        colors=cs,
        pctdistance=1.0)
    show()
Пример #8
0
class _AccPlot(object):
    Markers = ["o", "x", "-", ">", "<", "0"]
    Colors = mcm.Set1(range(len(Markers)))

    def __init__(self, preset_id=0):
        self.pid = preset_id

    def __plot_conf(self):
        m = self.Markers[self.pid]
        c = self.Colors[self.pid]
        return dict(marker=m, color=c)

    def __add_label(self, ax):
        ax.set_ylabel("Sensitivity", fontsize=14)
        ax.set_xlabel("Precision", fontsize=14)
        ax.set_title("Preprocessing ROC curve", fontsize=18, y=1.02)

    def plot(self, ax, data):
        conf = self.__plot_conf()
        data.plot(x="precision", y="sensitivity", ax=ax, **conf)
        self.__add_label(ax)
        for pi, pd in data.iterrows():
            x = pd.precision
            y = pd.sensitivity - .04
            ax.text(x, y, pd.key, ha='center', fontsize=14)
Пример #9
0
def plot_cells(cells, **kwargs):
    """
    Plot the spatial receptive fields for multiple cells.

    Parameters
    ----------
    cells : list of array_like
        A list of spatiotemporal receptive fields, each of which is a spatiotemporal array.

    ax : matplotlib Axes object, optional
        The axes onto which the ellipse should be plotted. Defaults to a new figure

    Returns
    ------
    fig : matplotlib.figure.Figure
        The figure onto which the ellipses are plotted.

    ax : matplotlib.axes.Axes
        The axes onto which the ellipses are plotted.
    """
    fig = kwargs.pop('fig')
    ax = kwargs.pop('ax')

    # for each cell
    for idx, sta in enumerate(cells):

        # get the spatial profile
        sp = ft.decompose(sta)[0]

        # plot ellipse
        color = cm.Set1(np.random.randint(100))
        fig, ax = ellipse(sp, fc=color, ec=color, lw=2, alpha=0.3, ax=ax)
Пример #10
0
 def correlationPlots(self, site=None):
     f, ax = plt.subplots()
     dFit = eucD(self.scores)
     dObs = self.obs
     if site is None:
         for i in range(len(self.obs)):
             ax.plot(dObs[i, :],
                     dFit[i, :],
                     'o',
                     alpha=0.5,
                     c=cm.Set1(float(i) / len(dObs), 1))
     else:
         ax.plot(dObs[site, :], dFit[site, :], 'ko', ms=0)
         [
             ax.text(x, y, str(s), ha='center', va='center')
             for x, y, s in zip(dObs[site, :], dFit[site, :],
                                range(len(dFit[site, :])))
         ]
         ax.set_title('Site {0}'.format(site))
     ax.set_ylabel("Fitted Distance to Site")
     ax.set_xlabel("Observed Distance to Site")
     ax.spines['top'].set_visible(False)
     ax.spines['right'].set_visible(False)
     ax.yaxis.set_ticks_position('left')
     ax.xaxis.set_ticks_position('bottom')
     plt.show()
Пример #11
0
def basic_plot(name: str,
               data: np.ndarray,
               labels: np.ndarray,
               xlabel: str = "x",
               ylabel: str = "y") -> None:

    plt.style.use("ggplot")
    fig, ax = plt.subplots()

    clusters = set(labels)
    num_ele = data.shape[0]
    num_clusters = len(clusters)

    ax.set_xlabel(xlabel, fontsize=15)
    ax.set_ylabel(ylabel, fontsize=15)
    ax.tick_params(labelsize=15)

    colors = [cm.Set1(lab + 1) for lab in labels]
    for i in range(num_clusters):
        cluster = list(clusters)[i]
        x = data[labels == cluster, 0]
        y = data[labels == cluster, 1]
        scatter = ax.scatter(x,
                             y,
                             color=np.array(colors)[labels == cluster],
                             label=str(int(cluster)))

    plt.tight_layout()
    plt.legend()
    plt.savefig(os.path.join(FIGURE_DIR, name))
    plt.show()
def gen_contribution_pie_plot(pie_plot_vals, pie_plot_labels, plot_loc,
                              criteria, extra_total_criteria, considered_jobs):
    print("Start contribution pie plot")
    plt.figure()
    a = np.random.random(11)
    cs = cm.Set1(np.arange(11) / 11.)
    patches, _, percent = plt.pie(pie_plot_vals,
                                  colors=cs,
                                  startangle=90,
                                  autopct='%1.1f%%',
                                  pctdistance=1.22)

    for i in range(len(pie_plot_labels)):
        pie_plot_labels[i] = pie_plot_labels[i] + '(' + percent[i].get_text(
        ) + ')'
    plt.legend(patches,
               pie_plot_labels,
               bbox_to_anchor=(1.2, 1.025),
               loc='upper left')
    if (criteria != 'length'):
        plt.title('Contribution of top 10 users with highest ' + criteria +
                  ' (Total ' + str(round(extra_total_criteria, 2)) + ' ' +
                  criteria)
    else:
        plt.title(
            'Contribution of top 10 users with highest job volume (Total ' +
            str(considered_jobs) + ' jobs)')
    plt.savefig(plot_loc + criteria + ' Contribution.png',
                bbox_inches="tight",
                dpi=300)
    print("Completed pie plot")
Пример #13
0
def model_dictionary():
    models = ['ACCESS1-0', 'ACCESS1-3', 'BNU-ESM','CCSM4', 'CESM1-BGC',\
       'CESM1-CAM5', 'CESM1-FASTCHEM', 'CESM1-WACCM', 'CMCC-CESM',\
       'CMCC-CM','CMCC-CMS', 'CNRM-CM5', 'CNRM-CM5','CNRM-CM5-2', 'CSIRO-Mk3-6-0', 'CanESM2',\
       'FGOALS-g2', 'FGOALS-s2', 'FIO-ESM', 'GFDL-CM3', 'GFDL-ESM2G',\
       'GFDL-ESM2M', 'GFDL-HIRAM-C180','GFDL-HIRAM-C360','GISS-E2-H*p1', 'GISS-E2-H*p3', 'GISS-E2-H-CC',\
       'GISS-E2-R*p1', 'GISS-E2-R*p3', 'GISS-E2-R-CC', 'HadCM3',\
       'HadGEM2-AO', 'HadGEM2-CC', 'HadGEM2-ES', 'IPSL-CM5A-LR',\
       'IPSL-CM5A-MR', 'IPSL-CM5B-LR', 'MIROC-ESM', 'MIROC-ESM-CHEM',\
       'MIROC4h', 'MIROC5', 'MPI-ESM-LR', 'MPI-ESM-MR', 'MPI-ESM-P','MRI-CGCM3',\
       'NorESM1-M', 'NorESM1-ME', 'bcc-csm1-1', 'bcc-csm1-1-m', 'fio-esm',\
       'inmcm4']
    markers =["o","v","^","<",">","8","s","p","*","h","H","D","d"]#,"P","X"]
    Lm = len(markers)
    d={}
    i=0
    colors = [cm.Set1(i/9.) for i in range(9)]+[cm.Set2(i/9.) for i in range(9)]+[cm.Set3(i/9.) for i in range(9)]
    Lc = len(colors)
    for i in range(len(models)):
        model =models[i]
        d[model]= {}
        d[model]["color"]=colors[np.mod(i,Lc)]
        d[model]["marker"]=markers[np.mod(i,Lm)]
    d["Can*"]=d["CanESM2"]
    d["CanAM4"]=d["CanESM2"]
    d["HadGEM2-A*"]=d["HadGEM2-AO"]
    d["HadGEM2-A"]=d["HadGEM2-AO"]
    return d
Пример #14
0
	def contribution_wav(self,wavlist,wav,h,tau5,Tsun, Icont,plot_cont=False,plot_hmean=False,hold=False,legends=True):
		plt.rc('text',usetex=True)
		plt.rc('font',**{'family':'serif','size':14})
		tau_idx = np.zeros(len(wavlist))
		hmean_arr = np.zeros(len(wavlist))
		colors = iter(cm.Set1(np.linspace(0, 1, len(wavlist))))
		contfunc_arr = np.zeros((len(wavlist),len(h)))
		tau_arr = np.zeros((len(wavlist),len(h)))
		hmean_arr = np.zeros(len(wavlist))
		intt_arr = np.zeros(len(wavlist))
		for i in range(len(wavlist)):
			contfunc_arr[i], intt_arr[i], hmean, tau_arr[i], wl=self.emergint(tau5,Tsun,wavlist[i])
			print 'computed continuum intensity wav =%g : %g erg s-1 cm-2 ster-1 cm-1'%(wl, intt_arr[i])
			w = np.where(wav == wl)
			print 'observed continuum intensity wav =%g : %g erg s-1 cm-2 ster-1 cm-1' %(wav[w], Icont[w]*1e10*1e4)
			print 'ratio Iobs/comp =', (Icont[w]*1e10*1e4)[0]/intt_arr[i]
			tau_idx[i] = np.argmin(np.abs(tau_arr[i]-1))
			hmean_arr[i] = hmean
			#print tau[int(tau_arr[i])]
		if plot_cont == True:
			[plt.plot(h,contfunc_arr[i]/np.amax(contfunc_arr[i]), label=r'$\lambda = $ '+str(wavlist[i])) for i in range(len(wavlist))]
			if plot_hmean == True:
				[plt.axvline(hmean_arr[i],ls='--',c=next(colors), label=r'$\langle h(\lambda=$'+str(wavlist[i])+r')$\rangle$') for i in range(len(wavlist))]

			plt.xlabel('height [km]')
			plt.ylabel('contribution function')
			if hold==False:
				if legends==True: plt.legend()
				plt.show()

		return tau_arr,tau_idx.astype(int),hmean_arr,intt_arr
Пример #15
0
def relate_point(X, i, ax):
    pt_i = X[i]
    for j, pt_j in enumerate(X):
        thickness = p_i(X, i)
        if i != j:
            line = ([pt_i[0], pt_j[0]], [pt_i[1], pt_j[1]])
            ax.plot(*line, c=cm.Set1(y[j]), linewidth=5 * thickness[j])
Пример #16
0
    def create_dataset(self, opt, means_x, std_x, name):
        means_x = list(means_x)
        variances_x = [np.eye(2) * std_x for _ in means_x]
        priors_x = [1.0 / len(means_x) for _ in means_x]

        dataset_x = sample_GMM(opt.dataset_size_x,
                               means_x,
                               variances_x,
                               priors_x,
                               sources=('features', ))
        save_path_x = opt.result_dir + name

        # plot_GMM(dataset, save_path)
        ##  reconstruced x

        X_dataset = dataset_x.data['samples']
        X_targets = dataset_x.data['label']

        self.set_means(means_x)
        self.set_priors(priors_x)
        self.set_variances(variances_x)
        self.set_dataset(X_dataset)

        fig_mx, ax = plt.subplots(nrows=1, ncols=1, figsize=(4.5, 4.5))
        ax.scatter(X_dataset[:, 0],
                   X_dataset[:, 1],
                   c=cm.Set1(X_targets.astype(float) / opt.input_dim / 2.0),
                   edgecolor='none',
                   alpha=0.5)
        ax.set_xlim(-3, 3)
        ax.set_ylim(-3.5, 3.5)
        ax.set_xlabel('$x_1$')
        ax.set_ylabel('$x_2$')
        ax.axis('on')
        plt.savefig(save_path_x, transparent=True, bbox_inches='tight')
Пример #17
0
    def create_dataset_test(self, opt, std_x, name):
        variances_x = self.get_variances()
        priors_x = self.get_priors()
        means_x = self.get_means()
        # create X dataset
        datasetX_test = sample_GMM(opt.dataset_size_x_test,
                                   means_x,
                                   variances_x,
                                   priors_x,
                                   sources=('features', ))
        save_path = opt.result_dir + name

        # plot_GMM(dataset, save_path)
        ##  reconstruced x

        X_np_data_test = datasetX_test.data['samples']
        X_targets_test = datasetX_test.data['label']

        self.set_dataset_test(X_np_data_test)
        self.set_label_test(X_targets_test)

        fig_mx, ax = plt.subplots(nrows=1, ncols=1, figsize=(4.5, 4.5))
        ax.scatter(X_np_data_test[:, 0],
                   X_np_data_test[:, 1],
                   c=cm.Set1(
                       X_targets_test.astype(float) / opt.input_dim / 2.0),
                   edgecolor='none',
                   alpha=0.5)
        ax.set_xlim(-3, 3)
        ax.set_ylim(-3.5, 3.5)
        ax.set_xlabel('$x_1$')
        ax.set_ylabel('$x_2$')
        ax.axis('on')
        plt.savefig(save_path, transparent=True, bbox_inches='tight')
Пример #18
0
def plot_GMM(dataset, save_path):
    figure, axes = plt.subplots(nrows=1, ncols=1, figsize=(4.5, 4.5))
    ax = axes
    ax.set_aspect('equal')
    ax.set_xlim(-3, 3)
    ax.set_ylim(-3.5, 3.5)
    # ax.set_xlim([-6, 6])
    # ax.set_ylim([-6, 6])
    # ax.set_xticks([-6, -4, -2, 0, 2, 4, 6])
    # ax.set_yticks([-6, -4, -2, 0, 2, 4, 6])
    # ax.set_xlabel('$x_1$')
    # ax.set_ylabel('$x_2$')
    ax.axis('on')

    ax.set_title('GMM')

    x = dataset.data['samples']
    targets = dataset.data['label']

    axes.scatter(x[:, 0],
                 x[:, 1],
                 marker='.',
                 c=cm.Set1(targets.astype(float) / 2.0 / 2.0),
                 alpha=0.3)
    plt.tight_layout()
    plt.savefig(save_path, transparent=True, bbox_inches='tight')
Пример #19
0
def make_pie(title, labels, sizes, num_rows, explode_index, angle):
    # explode index of the pie slice
    explode = make_explode(num_rows, explode_index)

    fig1, ax1 = plt.subplots()

    # set explode=None to turn off
    ax1.pie(sizes, labels=labels, labeldistance=1.2,
            explode=explode, autopct='%1.1f%%',
            shadow=True, startangle=angle)

    # matplot/ seaborn style setting
    mpl.rcParams['patch.force_edgecolor'] = True
    plt.rcParams["figure.figsize"] = (4, 4) # set fig size in inches

    # fig title
    fig1.suptitle(title, fontsize=13)

    # legend options
    # bbox_to_anchor(x0, y0, width, height)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

    # set color
    cs=cm.Set1(np.arange(40)/40.)

    # equal aspect ratio ensures that pie is drawn as a circle
    ax1.axis('equal')
Пример #20
0
def pie_chart(items, fname, ratio=None):
    """plot a pie chart of `items` (i.e slocs, licenses), a dictionary
    which maps a metric to a value. Save the obtained chart to `fname`

    """
    logging.debug('generate sloccount pie chart to %s...' % fname)
    cols = cm.Set1(np.arange(20) / 20.)
    plt.figure()
    keys, values = _split_series(list(six.iteritems(items)))
    modified_keys = ["Other: ", "Other"]
    modified_values = [0]
    for i, value in enumerate(values):
        if value > sum(values) * 2 / 100:
            modified_values.append(value)
            modified_keys.append(keys[i])
        else:
            modified_values[0] = (value + modified_values[0])
            modified_keys[0] = modified_keys[0] + keys[i].replace("_", ' ') \
                + " / "
            if len(modified_keys[0].split('\n')[-1]) > 50:
                modified_keys[0] = modified_keys[0] + "\n"
    # delete trailing /
    modified_keys[0] = modified_keys[0][0:-2]
    plt.pie(modified_values,
            labels=modified_keys[1:],
            autopct='%1.1f%%',
            colors=cols)
    if ratio:
        modified_keys[0] += '\nPercentage of files with non machine' \
                            ' readable d/copyright files  = ' \
                            + str(ratio) + '%'
    plt.figtext(.02, .02, modified_keys[0])
    plt.savefig(fname)
    plt.close()
Пример #21
0
def plot_quant_results(quant_dict, dirname):

    quant_dict['pos_tags']

    pos_attn_scores = [i[1][1] for i in quant_dict['pos_tags']]
    pos_count = [i[1][0] for i in quant_dict['pos_tags']]
    pos_tags = [i[0] for i in quant_dict['pos_tags']]
    print('pos tags', pos_tags)

    a = np.random.random(40)
    cs = cm.Set1(np.arange(10) / 10.)

    fig = plt.figure(figsize=(6, 6))
    plt.pie(pos_count,
            labels=pos_tags,
            colors=cs,
            explode=[0.1] * len(pos_count))
    plt.savefig(os.path.join(dirname, "quant_pos_count.png"))
    plt.show()

    fig = plt.figure(figsize=(6, 6))
    plt.pie(pos_attn_scores,
            labels=pos_tags,
            colors=cs,
            explode=[0.1] * len(pos_attn_scores))
    plt.savefig(os.path.join(dirname, "quant_pos_attn.png"))
    plt.show()
Пример #22
0
def make_dpl_from_construct(construct, showlabels=None):
    """ This function creats a dictionary suitable for
    input into dnaplotlib for plotting constructs.
    Inputs:
    construct: a DNA_construct object
    showlabels: list of part types to show labels for. For example, [AttachmentSite,Terminator]"""
    #TODO make showlabels more general
    if (showlabels is None):
        showlabels = []
    outdesign = []
    if (HAVE_MATPLOTLIB):
        cmap = cm.Set1(range(len(construct.parts_list) * 2))
    pind = 0
    for part in construct.parts_list:
        pcolor = part.color
        pcolor2 = part.color2
        if (HAVE_MATPLOTLIB):
            if (type(pcolor) == int):
                c1 = cmap[pcolor][:-1]
            else:
                c1 = cmap[pind][:-1]
            if (type(pcolor2) == int):
                c2 = cmap[pcolor2][:-1]
            else:
                c2 = cmap[random.choice(list(range(len(
                    construct.parts_list))))][:-1]
        showlabel = False
        if (type(part) in showlabels):
            showlabel = True
        outdesign+=make_dpl_from_part(part,direction = part.direction=="forward",\
                        color=c1,color2 =c2 ,showlabel=showlabel)
        pind += 1
    return outdesign
Пример #23
0
def show_final_balls(bt, show=False, savefile=None):

    fig, ax = get_custom_layout()
    leaves = get_leaves(bt)
    colors = cm.Set1(np.linspace(0, 1, len(leaves)))
    for i, leaf in enumerate(leaves):
        c, r, d = leaf.centroid, leaf.radius, leaf.node_data
        # ax.scatter(d[:, 0], d[:, 1], s=80, facecolors=colors[i], edgecolors='none', alpha=.7)
        # ax.scatter(c[0], c[1], s=160, facecolors=colors[i], edgecolors='none')
        add_scatter(ax,
                    d,
                    s=default_size,
                    facecolors=colors[i],
                    edgecolors='none',
                    alpha=.7)
        add_scatter(ax,
                    c,
                    s=centroid_size,
                    facecolors=colors[i],
                    edgecolors='none',
                    alpha=.7)
        pc = plt.Circle(xy=c[0], radius=r, color=colors[i], alpha=.2)
        ax.add_artist(pc)

    show_or_save(fig, show, savefile)
Пример #24
0
def sloc_pie(slocs, fname):
    """plot a pie chart of sloccount in `slocs`, a dictionary which maps
    language names to slocs. Save the obtained chart to `fname`

    """
    logging.debug('generate sloccount pie chart to %s...' % fname)
    cols = cm.Set1(np.arange(20) / 20.)
    plt.figure()
    langs, slocs = _split_series(list(six.iteritems(slocs)))
    modified_langs = ["Other: ", "Other"]
    modified_slocs = [0]
    for i, sloc in enumerate(slocs):
        if sloc > sum(slocs) * 2 / 100:
            modified_slocs.append(sloc)
            modified_langs.append(langs[i])
        else:
            modified_slocs[0] = (sloc + modified_slocs[0])
            modified_langs[0] = modified_langs[0] + " " + langs[i]
            if i % 12 == 0 and i != 0:
                modified_langs[0] = modified_langs[0] + "\n"
    plt.pie(modified_slocs,
            labels=modified_langs[1:],
            autopct='%1.1f%%',
            colors=cols)
    plt.figtext(.02, .02, modified_langs[0])
    plt.savefig(fname)
    plt.close()
Пример #25
0
def Publications_PerJournalNoPatents_Pie(journalsList):
    #piechart
    counter = dict()
    for subject in journalsList.keys():
        counter[subject] = Counter(journalsList[subject])
    fileName = [
        'Carbide Der. Carb.', 'Act.Carb.', 'Nanodiamond', 'Graphene',
        'Fullerene', 'Carb. Black', 'CNTs', 'Nano-onion', 'Aerogel', 'Graphite'
    ]
    allDicts = counter[fileName[0]] + counter[fileName[1]] + counter[
        fileName[2]] + counter[fileName[3]] + counter[fileName[4]] + counter[
            fileName[5]] + counter[fileName[6]] + counter[
                fileName[7]] + counter[fileName[8]] + counter[fileName[9]]

    counterOrd = OrderedDict(
        sorted(allDicts.items(), key=itemgetter(1), reverse=True))

    mainJournals = list()
    mainResults = list()
    othersResults = list()
    YvalY = list()
    LvalL = list()
    for item in counterOrd:
        if item != 'Google Patents' and item != 'US Patent' and item != 'patentimages.storage.googleapis. …':
            YvalY.append(counterOrd[item])
            LvalL.append(item)
        else:
            pass
    mainResults.append(YvalY[:20])
    mainJournals.append(LvalL[:20])
    othersResults.append(YvalY[21:])

    sumMain = sum(mainResults[0])
    sumOthers = sum(othersResults[0])

    x = mainResults[0]
    labels = mainJournals[0]

    a = np.random.random(40)
    cs = cm.Set1(np.arange(40) / 40.)
    f = plt.figure()
    ax = f.add_subplot(111, aspect='equal')

    #plt.suptitle('Journals excluding US Patents')
    plt.suptitle('Publicaciones de Revistas Excluyendo Patentes')
    plt.axis('equal')
    patches, texts, autotexts = ax.pie(x,
                                       labels=labels,
                                       autopct='%1.1f%%',
                                       shadow=True,
                                       startangle=90,
                                       colors=cs)
    propteaseP = fm.FontProperties()
    propteaseL = fm.FontProperties()
    propteaseP.set_size('xx-small')
    propteaseL.set_size('x-small')
    plt.setp(autotexts, fontproperties=propteaseP)
    plt.setp(texts, fontproperties=propteaseL)

    return plt.show()
Пример #26
0
def ShowCrimePieChart(filename):
    input_data = pd.read_csv(filename, header=0)
    df = pd.DataFrame(input_data)
    cs = cm.Set1(np.arange(40) / 40.)
    plt.figure(figsize=(16, 16))
    df['Primary Type'].value_counts(sort=True).plot.pie(
        title='Types of crimes', figsize=(16, 16), fontsize=8)
    plt.show()
Пример #27
0
def make_graph(A):
    G = nx.from_numpy_array(A)
    communities = community.greedy_modularity_communities(G)
    for idx, comm in enumerate(communities, 1):
        for node_idx in comm:
            G.nodes[node_idx]['community'] = idx
            G.nodes[node_idx]['color'] = cm.Set1(idx - 1)
    return G
Пример #28
0
def make_colours(num_items):
    """Generates colours for num_item items"""
    # We'll generate enough numbers between 0 and 1 and choose their colours from colormap Set1.
    # The use of float() is only needed for Python 2 (because it would otherwise be integer division).
    colornums = []
    for n in range(num_items):
        colornums.append(n / float(num_items))
    cs = cm.Set1(colornums)
    return cs
Пример #29
0
def ShowCrimeBarPlotByCommunity(filename):
    DisplayCrimeByAreaBarChart(filename)
    input_data = pd.read_csv(filename, header=0)
    df = pd.DataFrame(input_data)
    cs = cm.Set1(np.arange(40) / 40.)
    plt.figure(figsize=(16, 16))
    df['Community Area Name'].value_counts(sort=True).plot.bar(
        title='Crimes in Community', figsize=(16, 16), fontsize=8)
    plt.show()
Пример #30
0
def GeneratePieChart(label, values, title, fileName):
    labels = label
    fracs = values
    the_grid = GridSpec(1, 1)
    plt.subplot(the_grid[0, 0], aspect=1)
    cs = cm.Set1(np.arange(40) / 5.)
    plt.pie(fracs, labels=labels, autopct='%1.1f%%', colors=cs, shadow=True)
    plt.title(title)
    plt.savefig(fileName)