Python matplotlib.pyplot.rc() Examples

The following are code examples for showing how to use matplotlib.pyplot.rc(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: util.py    MIT License 6 votes vote down vote up
def reduce_dim(data_h, plot=False, save=False, c=None):
    
    if plot:
        # Scree plot
        plt.rc("font", size=12)
        pca = PCA()
        pca.fit(data_h)
        plt.plot(range(1,data_h.shape[1]+1), pca.explained_variance_ratio_)
        plt.xlabel('Dimensionality')
        plt.ylabel('Explained variance ratio')
        plt.title('Scree Plot')
        plt.show()
        plt.close()
    
    # Dimensionality reduction
    pca = PCA(n_components=.995) # 99.5% variance attained
    data_l = pca.fit_transform(data_h)
    print 'Reduced dimensionality: %d' % data_l.shape[1]
    if save:
        save_model(pca, 'xpca', c)
    
    return data_l, pca.inverse_transform 
Example 2
Project: bearing-vibration-diagnostics-toolbox   Author: andrek10   File: plt.py    MIT License 6 votes vote down vote up
def usetex(latex=False):
    '''
	Use latex font in figures
	
	Parameters
	----------
    latex : boolean, optional
        Turn off or on latex rendring
	
	Returns
	-------
	None
	'''

    plt.rc('font', **{'family': 'serif', 'serif': ['cm']})
    plt.rc('text', usetex=latex) 
Example 3
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_2d_hist(self,filename,title):
            from matplotlib.colors import LogNorm
            from matplotlib import cm
            import matplotlib.pyplot as plt
            #filename='rog_energy_top7.dat'
            font = {'family': 'serif',
                    'weight': 'normal',
                    'size': 10}
            plt.rc('font',**font)
            plt.rcParams["axes.linewidth"] = 2
            #plt.xlabel('Q',fontdict=font)

            plt.rc('ytick', labelsize=15)
            fig, ax = plt.subplots(figsize=(4,3))
            data = np.loadtxt(filename, dtype=float)
            x=data[:,0];y=data[:,1]
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
            plt.hist2d(x, y, bins=100, norm=LogNorm(),cmap=plt.cm.coolwarm)
            plt.xlabel('Q', fontdict=font)
            plt.colorbar()
            plt.show() 
Example 4
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_map(self,x,y,title,xaxis,yaxis):
            print ('>>in plot_map')
            #Simple x,y plot
            #X, Y are 1D numpy arrays
            maxx=max(x);maxy=max(y)
            plt.rcParams['backend'] = 'TkAgg'
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            plt.xlim(0,max(maxx,maxy))
            plt.ylim(0,max(maxx, maxy))#colors = ['k'] * len(x)
            ax.scatter(x, y ,alpha=0.5,s=10,linewidth=.05)
            plt.xlabel(xaxis)
            plt.ylabel(yaxis)
            #plt.savefig(title+'.png')
            plt.savefig(title + '.pdf')
            plt.rc('font', family='serif',size='20')
            #plt.show()
            print ('See: ',title+'.pdf')
            return 1 
Example 5
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_2d_hist(self,filename,title):
            from matplotlib.colors import LogNorm
            from matplotlib import cm
            import matplotlib.pyplot as plt
            #filename='rog_energy_top7.dat'
            font = {'family': 'serif',
                    'weight': 'normal',
                    'size': 10}
            plt.rc('font',**font)
            plt.rcParams["axes.linewidth"] = 2
            #plt.xlabel('Q',fontdict=font)

            plt.rc('ytick', labelsize=15)
            fig, ax = plt.subplots(figsize=(4,3))
            data = np.loadtxt(filename, dtype=float)
            x=data[:,0];y=data[:,1]
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
            plt.hist2d(x, y, bins=100, norm=LogNorm(),cmap=plt.cm.coolwarm)
            plt.xlabel('Q', fontdict=font)
            plt.colorbar()
            plt.show() 
Example 6
Project: gokit   Author: gokit1   File: table.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_table(self,x,E,f):
            # plt.style.use('ggplot')
            plt.rc('font', family='serif', size='20')
            zeroline = np.zeros(len(E))
            fig = plt.figure(figsize=(8, 6))
            ax = fig.add_subplot(1, 1, 1)
            plt.xlim([0, 4])
            plt.ylim([-2, 2])
            plt.xlim([1, 15])
            # plt.plot(x1,Eprime1)
            plt.plot(zeroline)
            ax.plot(x, E, color='k', ls='solid', label="E")
            ax.plot(x, f, color='b', ls='solid', label="Force")
            ax.plot(zeroline, color='g', ls='solid')
            plt.legend(loc=1, ncol=2, borderaxespad=0.2, fontsize=15)
            ax.set_xlabel('r')
            ax.set_ylabel('U(r)')
            plt.show()
            plt.close()
            return 
Example 7
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_map(self,x,y,title,xaxis,yaxis):
            print ('>>in plot_map')
            #Simple x,y plot
            #X, Y are 1D numpy arrays
            maxx=max(x);maxy=max(y)
            plt.rcParams['backend'] = 'TkAgg'
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            plt.xlim(0,max(maxx,maxy))
            plt.ylim(0,max(maxx, maxy))#colors = ['k'] * len(x)
            ax.scatter(x, y ,alpha=0.5,s=10,linewidth=.05)
            plt.xlabel(xaxis)
            plt.ylabel(yaxis)
            #plt.savefig(title+'.png')
            plt.savefig(title + '.pdf')
            plt.rc('font', family='serif',size='20')
            #plt.show()
            print ('See: ',title+'.pdf')
            return 1 
Example 8
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_scatter(self,x,y,title):
            #Simple x,y plot
            #X, Y are 1D numpy arrays
            import pylab
            plt.rcParams['backend'] = 'TkAgg'
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            #colors = ['k'] * len(x)
            ax.scatter(x, y,marker='o',markersize=1)
            plt.xlabel('X')
            plt.ylabel('Y')
            plt.savefig(title+'.png')
            plt.rc('font', family='serif', size='20')
            #plt.show()
            print ('See: ',title+'.png')
            return 1 
Example 9
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_2d_hist(self,filename,title):
            from matplotlib.colors import LogNorm
            from matplotlib import cm
            import matplotlib.pyplot as plt
            #filename='rog_energy_top7.dat'
            font = {'family': 'serif',
                    'weight': 'normal',
                    'size': 10}
            plt.rc('font',**font)
            plt.rcParams["axes.linewidth"] = 2
            #plt.xlabel('Q',fontdict=font)

            plt.rc('ytick', labelsize=15)
            fig, ax = plt.subplots(figsize=(4,3))
            data = np.loadtxt(filename, dtype=float)
            x=data[:,0];y=data[:,1]
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
            plt.hist2d(x, y, bins=100, norm=LogNorm(),cmap=plt.cm.coolwarm)
            plt.xlabel('Q', fontdict=font)
            plt.colorbar()
            plt.show() 
Example 10
Project: gokit   Author: gokit1   File: plots.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_prcontact_map(self,filename,file1):
        #plot probability contact-map
        font=self.set_font()
        plt.rc('font', **font)
        plt.rcParams["axes.linewidth"] = 1
        data = np.loadtxt(filename, dtype=float)
        data1 = np.loadtxt(file1,dtype=float)
        cm = matplotlib.cm.get_cmap('inferno_r')
        x = data[:, 0];y = data[:, 1];z = data[:,2]
        x1 = data1[:, 0];y1 = data1[:, 1]; z1 = data1[:, 2]
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        sc = ax.scatter(x, y, c=z, vmin=0.20, vmax=1, marker='s', s=10, cmap=cm)
        ax.scatter(y1,x1, c=z1, vmin=0.20, vmax=1, marker='s', s=10, cmap=cm)
        #xtics=np.arange(0,92,20)
        #plt.xticks(xtics)
        plt.colorbar(sc)
        plt.grid()
        plt.savefig(filename+'.eps', format='eps', dpi=1000)
        plt.show() 
Example 11
Project: gokit   Author: gokit1   File: plots.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_scatter(self, x, y, title):
        # Simple x,y plot
        # X, Y are 1D numpy arrays
        plt.rcParams['backend'] = 'TkAgg'
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        # colors = ['k'] * len(x)
        ax.scatter(x, y, marker='o')
        ax.plot(x,y,'-o')
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.savefig(title + '.png')
        plt.rc('font', family='serif', size='20')
        plt.show()
        print ('See: ', title + '.png')
        return True 
Example 12
Project: hrt   Author: tansey   File: sim_predictors_importance.py    MIT License 6 votes vote down vote up
def p_plot(p_values, labels, start=0, end=1):
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.rc('xtick', labelsize=14)
        plt.rc('ytick', labelsize=14)
        matplotlib.rcParams['pdf.fonttype'] = 42
        matplotlib.rcParams['ps.fonttype'] = 42
        for p, label in zip(p_values, labels):
            p = np.array(p)
            p = p[~np.isnan(p)]
            p = np.sort(p)
            print(p.shape)
            x = np.concatenate([[0],p,[1]])
            y = np.concatenate([[0],(np.arange(p.shape[0])+1.)/p.shape[0],[1]])
            plt.plot(x, y, label=label, lw=2)
        plt.plot([0,1], [0,1], color='black', ls='--', lw=3, label='U(0,1)', alpha=0.7)
        plt.xlim([start,end])
        plt.ylim([start,end])
        plt.xlabel('p-value', fontsize=18, weight='bold')
        plt.ylabel('Empirical CDF', fontsize=18, weight='bold')
        plt.legend(loc='lower right') 
Example 13
Project: hrt   Author: tansey   File: sim_predictors_order.py    MIT License 6 votes vote down vote up
def p_plot(p_values, labels, start=0, end=1):
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.rc('xtick', labelsize=14)
        plt.rc('ytick', labelsize=14)
        matplotlib.rcParams['pdf.fonttype'] = 42
        matplotlib.rcParams['ps.fonttype'] = 42
        for p, label in zip(p_values, labels):
            p = np.array(p)
            p = p[~np.isnan(p)]
            p = np.sort(p)
            print(p.shape)
            x = np.concatenate([[0],p,[1]])
            y = np.concatenate([[0],(np.arange(p.shape[0])+1.)/p.shape[0],[1]])
            plt.plot(x, y, label=label, lw=2)
        plt.plot([0,1], [0,1], color='black', ls='--', lw=3, label='U(0,1)', alpha=0.7)
        plt.xlim([start,end])
        plt.ylim([start,end])
        plt.xlabel('p-value', fontsize=18, weight='bold')
        plt.ylabel('Empirical CDF', fontsize=18, weight='bold')
        plt.legend(loc='lower right') 
Example 14
Project: hrt   Author: tansey   File: sim_predictors_order.py    MIT License 6 votes vote down vote up
def order_vs_p_scatter(orders, p, n, c):
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        ntests = len(order[0])
        buckets = np.zeros((len(order), ntests))
        for trial_idx, (trial_order, trial_p) in enumerate(zip(order, p)):
            buckets[trial_idx, trial_order] = trial_p
        plt.plot(np.arange(ntests)+1, buckets.mean(axis=0), color=c)
        plt.fill_between(np.arange(ntests)+1,
                         buckets.mean(axis=0) - buckets.std(axis=0),
                         buckets.mean(axis=0) + buckets.std(axis=0),
                         color=c,
                         alpha=0.7)
        plt.xlabel('Heuristic rank', fontsize=18, weight='bold')
        plt.ylabel('$\\mathbf{p}$-value', fontsize=18, weight='bold') 
Example 15
Project: hrt   Author: tansey   File: sim_predictors_agg.py    MIT License 6 votes vote down vote up
def r2_scatter(tpr_vals, r2_vals, names):
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        # order = np.argsort([np.mean(r) if len(r) > 0 else 1 for r in r2_vals])
        # for idx in order:
            # plt.scatter(r2_vals[idx], tpr_vals[idx], label=names[idx])
        for t, r, n in zip(tpr_vals, r2_vals, names):
            plt.scatter(r, t, label=n)
        plt.xlabel('Cross-validation $\\mathbf{r^2}$', fontsize=18, weight='bold')
        plt.ylabel('Power', fontsize=18, weight='bold')
        plt.xlim([0.8, 1])
        plt.xticks([0.8, 0.85, 0.9, 0.95, 1], ['0.8', '0.85', '0.9', '0.95', '1'])
        # plt.legend(loc='upper left', ncol=2) 
Example 16
Project: Bayesian_Optimization_Material_design   Author: rajak7   File: predict_structure.py    GNU General Public License v3.0 6 votes vote down vote up
def plotbandtest(XX,structure,YY1true,YY2true,YY1predict,YY2predict,YY1sigma,YY2sigma,myid):
    fig = plt.figure(figsize=(10,10))
    plt.rc('xtick', labelsize=20)
    plt.rc('ytick', labelsize=20)
    plt.rc('font', weight='bold')
    plt.plot(XX, YY1true, 'b-', linewidth=3.5, label=u'CBM-Ground-Truth')
    plt.plot(XX, YY1predict, 'c--', linewidth=3.5)
    #plt.fill(np.concatenate([XX, XX[::-1]]),np.concatenate([YY1predict - 1.9600 * YY1sigma, (YY1predict + 1.9600 * YY1sigma)[::-1]]), alpha=.3, fc='y', ec='None',label='95% confidence interval')
    plt.plot(XX, YY2true, 'r-', linewidth=3.5, label=u'VBM-Ground-Truth')
    plt.plot(XX, YY2predict, 'm--', linewidth=3.5)
    #plt.fill(np.concatenate([XX, XX[::-1]]),np.concatenate([YY2predict - 1.9600 * YY2sigma, (YY2predict + 1.9600 * YY2sigma)[::-1]]), alpha=.3, fc='g',ec='None', label='95% confidence interval')
    plt.title(structure, fontsize=20, fontweight='bold')
    plt.legend(loc='upper right', bbox_to_anchor=(0.28, 1.16), ncol=1, fancybox=True, shadow=True, prop={'size': 14})
    plt.xlabel('Wave Vector',fontsize=20, fontweight='bold')
    plt.ylabel('Energy(eV)',fontsize=20, fontweight='bold')
    imagefile = "Bandstructure/Strucuture" + str(myid+1)
    plt.savefig(imagefile)
#    plt.show()

#Build GP regression model 
Example 17
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_rc_tick():
    d = {'xtick.bottom': False, 'xtick.top': True,
         'ytick.left': True, 'ytick.right': False}
    with plt.rc_context(rc=d):
        fig = plt.figure()
        ax1 = fig.add_subplot(1, 1, 1)
        xax = ax1.xaxis
        yax = ax1.yaxis
        # tick1On bottom/left
        assert not xax._major_tick_kw['tick1On']
        assert xax._major_tick_kw['tick2On']
        assert not xax._minor_tick_kw['tick1On']
        assert xax._minor_tick_kw['tick2On']

        assert yax._major_tick_kw['tick1On']
        assert not yax._major_tick_kw['tick2On']
        assert yax._minor_tick_kw['tick1On']
        assert not yax._minor_tick_kw['tick2On'] 
Example 18
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_rc_major_minor_tick():
    d = {'xtick.top': True, 'ytick.right': True,  # Enable all ticks
         'xtick.bottom': True, 'ytick.left': True,
         # Selectively disable
         'xtick.minor.bottom': False, 'xtick.major.bottom': False,
         'ytick.major.left': False, 'ytick.minor.left': False}
    with plt.rc_context(rc=d):
        fig = plt.figure()
        ax1 = fig.add_subplot(1, 1, 1)
        xax = ax1.xaxis
        yax = ax1.yaxis
        # tick1On bottom/left
        assert not xax._major_tick_kw['tick1On']
        assert xax._major_tick_kw['tick2On']
        assert not xax._minor_tick_kw['tick1On']
        assert xax._minor_tick_kw['tick2On']

        assert not yax._major_tick_kw['tick1On']
        assert yax._major_tick_kw['tick2On']
        assert not yax._minor_tick_kw['tick1On']
        assert yax._minor_tick_kw['tick2On'] 
Example 19
Project: ble5-nrf52-mac   Author: tomasero   File: test_backend_ps.py    MIT License 6 votes vote down vote up
def test_tilde_in_tempfilename(tmpdir):
    # Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows
    # when the username is very long and windows uses a short name) breaks
    # latex before https://github.com/matplotlib/matplotlib/pull/5928
    base_tempdir = Path(str(tmpdir), "short-1")
    base_tempdir.mkdir()
    # Change the path for new tempdirs, which is used internally by the ps
    # backend to write a file.
    with cbook._setattr_cm(tempfile, tempdir=str(base_tempdir)):
        # usetex results in the latex call, which does not like the ~
        plt.rc('text', usetex=True)
        plt.plot([1, 2, 3, 4])
        plt.xlabel(r'\textbf{time} (s)')
        output_eps = os.path.join(str(base_tempdir), 'tex_demo.eps')
        # use the PS backend to write the file...
        plt.savefig(output_eps, format="ps") 
Example 20
Project: chicago-crime   Author: thekingofkings   File: multi_view_prediction.py    MIT License 6 votes vote down vote up
def plot_hourly_crime():
    plt.rc("axes", linewidth=2)
    plt.figure(figsize=(8,6))
    for year in range(2013, 2016):
        Y, D, P, T, G = extract_raw_samples(year)
        population = D[:,0]
        
        Yh = pickle.load(open("../chicago-hourly-crime-{0}.pickle".format(year)))
        Yh = Yh / population * 10000
        if year == 2015:
            Yh = Yh * 2
        plt.plot(Yh.mean(axis=1), lw=3)
        
    plt.legend(["2013", "2014", "2015"], fontsize=20, loc='best')
    plt.xlabel("Hour in day", fontsize=20)
    plt.ylabel("Average crime rate", fontsize=24)
    plt.axis([0,23,10,70])
    plt.gca().set_xticks([0,6,12,18,23])
    plt.gca().set_xticklabels(("0:00", "6:00", "12:00", "18:00", "23:00"))
    plt.grid(b=True, axis="both", lw=1)
    plt.tick_params(labelsize=18)
    plt.savefig("crime-rate-hourly.pdf") 
Example 21
Project: ransX   Author: mmicromegas   File: ResMasterPlot.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def SetMatplotlibParams(self):
        """ This routine sets some standard values for matplotlib """ 
        """ to obtain publication-quality figures """

        # plt.rc('text',usetex=True)
        # plt.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
        plt.rc('font',**{'family':'serif','serif':['Times New Roman']})
        plt.rc('font',size=16.)
        plt.rc('lines',linewidth=2,markeredgewidth=2.,markersize=12)
        plt.rc('axes',linewidth=1.5)
        plt.rcParams['xtick.major.size']=8.
        plt.rcParams['xtick.minor.size']=4.
        plt.rcParams['figure.subplot.bottom']=0.15
        plt.rcParams['figure.subplot.left']=0.17		
        plt.rcParams['figure.subplot.right']=0.85
        plt.rcParams.update({'figure.max_open_warning': 0}) 
Example 22
Project: ransX   Author: mmicromegas   File: MasterPlot.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def SetMatplotlibParams(self):
        """ This routine sets some standard values for matplotlib """ 
        """ to obtain publication-quality figures """

        # plt.rc('text',usetex=True)
        # plt.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
        plt.rc('font',**{'family':'serif','serif':['Times New Roman']})
        plt.rc('font',size=16.)
        plt.rc('lines',linewidth=2,markeredgewidth=2.,markersize=12)
        plt.rc('axes',linewidth=1.5)
        plt.rcParams['xtick.major.size']=8.
        plt.rcParams['xtick.minor.size']=4.
        plt.rcParams['figure.subplot.bottom']=0.15
        plt.rcParams['figure.subplot.left']=0.17		
        plt.rcParams['figure.subplot.right']=0.85
        plt.rcParams.update({'figure.max_open_warning': 0}) 
Example 23
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def _initialisePlot(self):

        plt.rc('grid', linestyle=":", color='black')
        plt.rcParams['axes.facecolor'] = 'black'
        plt.rcParams['axes.edgecolor'] = 'white'
        plt.rcParams['grid.alpha'] = 1
        plt.rcParams['grid.color'] = "green"
        plt.grid(True)
        plt.xlim(self.PLOTXMIN, self.PLOTXMAX)
        plt.ylim(self.PLOTYMIN, self.PLOTYMAX)
        self.graph, = plt.plot([], [], 'o')

        return 
Example 24
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_box_plot(data, names, title):
    """
    Given an array of some data, and a list of names of that data, generate
    and save a box plot of that data.

    :param data: An array of some data to be plotted.
    :param names: A list of names of that data.
    :param title: The title of the plot.
    :return: Nothing
    """

    from algorithm.parameters import params

    import matplotlib.pyplot as plt
    plt.rc('font', family='Times New Roman')

    # Set up the figure.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot tight layout.
    plt.tight_layout()

    # Plot the data.
    ax1.boxplot(np.transpose(data), 1)

    # Plot title.
    plt.title(title)

    # Generate list of numbers for plotting names.
    nums = list(range(len(data))[1:]) + [len(data)]

    # Plot names for each data point.
    plt.xticks(nums, names, rotation='vertical', fontsize=8)

    # Save plot.
    plt.savefig(path.join(params['FILE_PATH'], (title + '.pdf')))

    # Close plot.
    plt.close() 
Example 25
Project: EXOSIMS   Author: dsavransky   File: plotTimeline.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prettyPlot(self):
        """ Makes Plots Pretty
        """
        plt.rc('axes',linewidth=2)
        plt.rc('lines',linewidth=2)
        plt.rcParams['axes.linewidth']=2
        plt.rc('font',weight='bold') 
Example 26
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: util.py    MIT License 5 votes vote down vote up
def get_candidate(X, dim, k_min, k_max, verbose=0):
    errs = []
    k_candidates = []
    for k in range(k_min, k_max+1):
        isomap = Isomap(n_neighbors=k, n_components=dim).fit(X)
        rec_err = isomap.reconstruction_error()
        errs.append(rec_err)
        i = k - k_min
        if i > 1 and errs[i-1] < errs[i-2] and errs[i-1] < errs[i]:
            k_candidates.append(k-1)
            
    if len(k_candidates) == 0:
        k_candidates.append(k)
        
    if verbose == 2:
        print 'k_candidates: ', k_candidates
    
        plt.figure()
        plt.rc("font", size=12)
        plt.plot(range(k_min, k_max+1), errs, '-o')
        plt.xlabel('Neighborhood size')
        plt.ylabel('Reconstruction error')
        plt.title('Select candidates of neighborhood size')
        plt.show()
        
    return k_candidates 
Example 27
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: util.py    MIT License 5 votes vote down vote up
def pick_k(X, dim, k_min=None, k_max=None, verbose=0):
    ''' Pick optimal neighborhood size for isomap algothm
    Reference:
    Samko, O., Marshall, A. D., & Rosin, P. L. (2006). Selection of the optimal parameter 
    value for the Isomap algorithm. Pattern Recognition Letters, 27(9), 968-979.
    '''
    
    if k_min is None or k_max is None:
        k_min, k_max = get_k_range(X, verbose=verbose)
    
    ccs = []
    k_candidates = range(k_min, k_max+1)#get_candidate(X, dim, k_min, k_max, verbose=verbose)
    for k in k_candidates:
        isomap = Isomap(n_neighbors=k, n_components=dim).fit(X)
        F = isomap.fit_transform(X)
        distF = pairwise_distances(F)
        distX = create_graph(X, k, verbose=verbose)
        cc = 1-pearsonr(distX.flatten(), distF.flatten())[0]**2
        ccs.append(cc)
       
    k_opt = k_candidates[np.argmin(ccs)]
    
    if verbose == 2:
        print 'k_opt: ', k_opt
        
        plt.figure()
        plt.rc("font", size=12)
        plt.plot(k_candidates, ccs, '-o')
        plt.xlabel('Neighborhood size')
        plt.ylabel('Residual variance')
        plt.title('Select optimal neighborhood size')
        plt.show()
    
    return k_opt 
Example 28
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: util.py    MIT License 5 votes vote down vote up
def estimate_dim(data, verbose=0):
    ''' Estimate intrinsic dimensionality of data
    data: input data
    Reference:
    "Samko, O., Marshall, A. D., & Rosin, P. L. (2006). Selection of the optimal parameter 
    value for the Isomap algorithm. Pattern Recognition Letters, 27(9), 968-979."
    '''
    # Standardize by center to the mean and component wise scale to unit variance
    data = scale(data)
    # The reconstruction error will decrease as n_components is increased until n_components == intr_dim
    errs = []
    found = False
    k_min, k_max = get_k_range(data, verbose=verbose)
    for dim in range(1, data.shape[1]+1):
        k_opt = pick_k(data, dim, k_min, k_max, verbose=verbose)  
        isomap = Isomap(n_neighbors=k_opt, n_components=dim).fit(data)
        err = isomap.reconstruction_error()
        #print(err)
        errs.append(err)
        
        if dim > 2 and errs[dim-2]-errs[dim-1] < .5 * (errs[dim-3]-errs[dim-2]):
                intr_dim = dim-1
                found = True
                break
        
    if not found:
        intr_dim = 1
        
#        intr_dim = find_gap(errs, method='difference', verbose=verbose)[0] + 1
#        intr_dim = find_gap(errs, method='percentage', threshold=.9, verbose=verbose) + 1

    if verbose == 2:
        plt.figure()
        plt.rc("font", size=12)
        plt.plot(range(1,dim+1), errs, '-o')
        plt.xlabel('Dimensionality')
        plt.ylabel('Reconstruction error')
        plt.title('Select intrinsic dimension')
        plt.show()
    
    return intr_dim 
Example 29
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: shape_plot.py    MIT License 5 votes vote down vote up
def plot_original_samples(points_per_axis, n_dim, inverse_transform, save_path, name,
                          variables, mirror=True):
    
    print "Plotting original samples ..."

    plt.rc("font", size=font_size)
    
    coords = variables
    coords_norm = preprocessing.MinMaxScaler().fit_transform(coords) # Min-Max normalization
    data_rec = inverse_transform(np.array(coords))
    indices = range(len(coords))

    if n_dim == 2:
        # Create a 2D plot
        fig = plt.figure()
        ax = fig.add_subplot(111)
        for i in indices:
            ax.scatter(coords_norm[i, 0], coords_norm[i, 1], s = 7)
            plot_shape(data_rec[i], coords_norm[i,0], coords_norm[i,1], ax, mirror, color='red', alpha=.7)

        ax.set_title(name, fontsize=20)
        plt.xlim(-0.1, 1.1)
        plt.ylim(-0.1, 1.1)
        plt.xlabel('s')
        plt.ylabel('t')
        plt.tight_layout()
        plt.savefig(save_path+'original_samples.eps', dpi=600)
        
        plt.close()
		
    else:
        print 'Cannot plot original samples for dimensionality other than 2!' 
Example 30
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_map(self,x,y,title,xaxis,yaxis):
            print ('>>in plot_map')
            #Simple x,y plot
            #X, Y are 1D numpy arrays
            maxx=max(x);maxy=max(y)
            plt.rcParams['backend'] = 'TkAgg'
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            plt.xlim(0,max(maxx,maxy))
            plt.ylim(0,max(maxx, maxy))#colors = ['k'] * len(x)
            ax.scatter(x, y ,alpha=0.5,s=10,linewidth=.05)
            plt.xlabel(xaxis)
            plt.ylabel(yaxis)
            #plt.savefig(title+'.png')
            plt.savefig(title + '.pdf')
            plt.rc('font', family='serif',size='20')
            #plt.show()
            print ('See: ',title+'.pdf')
            return 1 
Example 31
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_scatter(self,x,y,title):
            #Simple x,y plot
            #X, Y are 1D numpy arrays
            import pylab
            plt.rcParams['backend'] = 'TkAgg'
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            #colors = ['k'] * len(x)
            ax.scatter(x, y,marker='o',markersize=1)
            plt.xlabel('X')
            plt.ylabel('Y')
            plt.savefig(title+'.png')
            plt.rc('font', family='serif', size='20')
            #plt.show()
            print ('See: ',title+'.png')
            return 1 
Example 32
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_histogram(self,x,title):
            import matplotlib.pyplot as plt
            #x=np.histogram(x, bins=np.arange(0,1,len(x)), density=True)
            noise = x
            num_bins = 100
            n, bins, _ = plt.hist(noise, num_bins, histtype='step')
            plt.hist(n,bins,normed=True,linestyle=('dashed'),color=('red'),label='pop')
            #!plt.legend(loc=1, ncol=2, borderaxespad=0.2, fontsize=15)
            plt.rc('font', family='serif', size='20')
            plt.style.use('ggplot')
            plt.savefig(title + '.pdf')
            print ("See file:", title+'.pdf')
            #plt.show() 
Example 33
Project: gokit   Author: gokit1   File: conmaps.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_histogram(self,x,title):
            import matplotlib.pyplot as plt
            #x=np.histogram(x, bins=np.arange(0,1,len(x)), density=True)
            noise = x
            num_bins = 100
            n, bins, _ = plt.hist(noise, num_bins, histtype='step')
            plt.hist(n,bins,normed=True,linestyle=('dashed'),color=('red'),label='pop')
            #!plt.legend(loc=1, ncol=2, borderaxespad=0.2, fontsize=15)
            plt.rc('font', family='serif', size='20')
            plt.style.use('ggplot')
            plt.savefig(title + '.pdf')
            print ("See file:", title+'.pdf')
            #plt.show() 
Example 34
Project: gokit   Author: gokit1   File: plots.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_contact_map(self,f1,f2,f3,f4):
        #plot up to 5 files. #fig1 to show contact-maps.
        #files in SMOG.contacts format
        font=self.set_font()
        plt.rc('font', **font)
        plt.rcParams["axes.linewidth"] = 1
        #top half
        d1 = np.loadtxt(f1, dtype=float);x1 = d1[:, 1];y1 = d1[:, 3]
        d2 = np.loadtxt(f2, dtype=float);x2 = d2[:, 1];y2 = d2[:, 3]
        #bottom half
        d3 = np.loadtxt(f3, dtype=float);x3 = d3[:, 1];y3 = d3[:, 3]
        d4 = np.loadtxt(f4, dtype=float);x4 = d4[:, 1];y4 = d4[:, 3]
        #d5 = np.loadtxt(f5, dtype=float);x5 = d5[:, 0];y5 = d5[:, 1]
        # x3 = x3 + 1;
        # y3 = y3 + 1;
        # x4 = x4 + 1;
        # y4 = y4 + 1;
        #x5 = x5 + 1;
        #y5 = y5 + 1
        fig = plt.figure(figsize=(6,6))
        ax = fig.add_subplot(1, 1, 1)

        #add diagonal
        diag1=np.arange(0,201,100)
        diag1=np.arange(0,100,10)

        a1 = ax.scatter(x1, y1, marker='s', s=10,color='#ff7f0e')
        a2 = ax.scatter(x2, y2, marker='s', s=20,color='#1f77b4')
        a3 = ax.scatter(y3, x3, marker='s', s=10,color='#ff7f0e')
        d1 = ax.plot(diag1,diag1, c="darkgray", marker=' ', linestyle='-',linewidth=2)

        a4 = ax.scatter(y4, x4, marker='s', s=20,color='#1f77b4')
        #a5 = ax.scatter(y5, x5, marker='s', s=25, color='black', facecolors='none')
        xtics=np.arange(0,101,40)
        ytics = np.arange(0, 101, 40)

        plt.xticks(xtics)
        plt.yticks(ytics)
        legend=plt.legend((a1,a2,a3,a4),('4.5','SCM'),fontsize=15,bbox_to_anchor=(-0.23,1.02,1,0.1), loc="lower left",ncol=5,frameon=False,handletextpad=0.0)
        plt.savefig('conmap'+'.eps', format='eps', dpi=1000)
        plt.show() 
Example 35
Project: gokit   Author: gokit1   File: plots.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_lines(self,f1,f2,f3,f4,f5,f6,title):
        font = self.set_font()
        d1 = np.loadtxt(f1);x1 = d1[:, 0];y1 = d1[:, 1]
        d2 = np.loadtxt(f2);x2 = d2[:, 0];y2 = d2[:, 1]
        d3 = np.loadtxt(f3);x3 = d3[:, 0];y3 = d3[:, 1]
        d4 = np.loadtxt(f4);x4 = d4[:, 0];y4 = d4[:, 1]
        d5 = np.loadtxt(f5);x5 = d5[:, 0];y5 = d5[:, 1]
        d6 = np.loadtxt(f6);x6 = d6[:, 0];y6 = d6[:, 1]


        plt.rc('font', **font)
        plt.rcParams['backend'] = 'TkAgg'
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        # colors = ['k'] * len(x)
        #ax.scatter(x1, y1, marker='o')
        ax.plot(x1, y1+195.0197020000, '-',label='cut-off',color='#ff7f0e')
        ax.plot(x2, y2+199.0028432000, '--', label='cut-off+hp',color='#ff7f0e')
        ax.plot(x3, y3+254.9241883000, '-', label='SCM',color='#1f77b4')
        ax.plot(x4, y4+258.9067123000 ,'--', label='SCM+hp',color='#1f77b4')
        ax.plot(x5, y5+194.4277855000, '-', label='dsb',color='#2ca02c')
        ax.plot(x6, y6+198.4674764000, '--', label='dsb+hp',color='#2ca02c')
        plt.ylim((0, 200))
        plt.title(title)
        plt.savefig(title + '.eps', format='eps', dpi=1000)
        plt.rc('font', family='serif', size='20')
        plt.legend(frameon=False, fontsize=10)
        plt.show()
        return True 
Example 36
Project: photograv   Author: hippke   File: photograv.py    MIT License 5 votes vote down vote up
def make_figure_distance_pitch_angle(data, scale, stellar_radius):

    encounter_time, step_of_closest_encounter = get_closest_encounter(data)

    # select data from start to closest encounter
    stellar_radii = sun_radius / stellar_radius
    px_stellar_units = data['px'][:step_of_closest_encounter] * stellar_radii
    py_stellar_units = data['py'][:step_of_closest_encounter] * stellar_radii
    pitch_angle = data['alpha'][:step_of_closest_encounter]
    pitch_angle = -numpy.degrees(pitch_angle)

    # distance between sail and origin in [m]
    distance = sqrt((px_stellar_units**2) + (py_stellar_units**2))

    # make figure
    fig = plt.figure(figsize=(6, 6))
    ax = plt.gca()
    fig.suptitle('b', fontsize=14, fontweight='bold', x=0.131, y=0.95)
    plt.plot(distance, pitch_angle, linewidth=0.5, color='black')
    plt.xscale('log')
    ax.set_xticks([5, 10, 100])
    ax.set_xticklabels(["50", "10", "100"])
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    plt.xlim(4, 100)
    plt.ylim(-45, 0)
    plt.xlabel('Stellar Distance [Stellar Radii]', fontweight='bold')
    plt.ylabel(
        r'Sail Pitch Angle $\alpha$ During Approach [Degrees]',
        fontweight='bold')
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    return plt 
Example 37
Project: practical-oct   Author: TheoryInPractice   File: plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_oct(dataframe, output_filename):
    sns.set_style("darkgrid")

    # Use latex text
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    # Define color palette
    colors = ["dusty purple", "windows blue", "amber", "faded green"]
    palette = sns.xkcd_palette(colors)

    # Make plot
    solver_order = ['OCT-1T', 'OCT-4T']

    g = sns.FacetGrid(data=dataframe,
                      col="Solver",
                      col_order=solver_order,
                      col_wrap=2,
                      hue='Regime',
                      hue_order=['Timed Out', 'Identical', 'Slower'],
                      height=2.3,
                      aspect=1.7,
                      palette=palette)
    g = (g.map(sns.scatterplot, "Dataset ID", "Relative Run Time")
         .add_legend())

    g.set(yscale='log')
    plt.ylim(0.5, 200000)

    # Update titles
    titles = ['OCT-1T', 'OCT-4T']
    for axis in g.fig.axes:
        axis.set_title(titles.pop(0))

    # Facet titles
    g.set_ylabels(r'\textbf{Run Time Ratio}')
    g.set_xlabels(r'\textbf{Dataset ID (Sorted by VC-1T)}')

    # Save plot
    g.savefig(output_filename) 
Example 38
Project: practical-oct   Author: TheoryInPractice   File: plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_vc(dataframe, output_filename):
    sns.set_style("darkgrid")

    # Use latex text
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    # Define color palette
    colors = ["windows blue", "amber", "faded green"]
    palette = sns.xkcd_palette(colors)

    # Make plot
    solver_order = ['VC-4T']

    g = sns.FacetGrid(data=dataframe,
                      col="Solver",
                      col_order=solver_order,
                      hue='Regime',
                      hue_order=['Identical', 'Slower', 'Faster'],
                      height=2.3,
                      aspect=1.7,
                      palette=palette)
    g = (g.map(sns.scatterplot, "Dataset ID", "Relative Run Time")
         .add_legend())

    g.set(yscale='log')
    plt.ylim(0.01, 10)

    # Update titles
    titles = ['VC-4T']
    for axis in g.fig.axes:
        axis.set_title(titles.pop(0))

    # Facet titles
    g.set_ylabels(r'\textbf{Run Time Ratio}')
    g.set_xlabels(r'\textbf{Dataset ID (Sorted by VC-1T)}')

    # Save plot
    g.savefig(output_filename) 
Example 39
Project: practical-oct   Author: TheoryInPractice   File: plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_vc_runtime(dataframe, output_filename):
    sns.set_style("darkgrid")

    # Use latex text
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    # Define color palette
    colors = ["windows blue"]
    palette = sns.xkcd_palette(colors)

    # Make plot
    solver_order = ['VC-1T']

    g = sns.FacetGrid(data=dataframe,
                      col="Solver",
                      col_order=solver_order,
                      height=2.3,
                      aspect=1.7,
                      palette=palette)
    g = (g.map(sns.scatterplot, "Dataset ID", "Time").add_legend())

    g.set(yscale='log')
    plt.ylim(0.0005, 10000)

    # Update titles
    titles = ['VC-1T']
    for axis in g.fig.axes:
        axis.set_title(titles.pop(0))

    # Facet titles
    g.set_ylabels(r'\textbf{Run Time (sec)}')
    g.set_xlabels(r'\textbf{Dataset ID (Sorted by VC-1T)}')

    # Save plot
    g.savefig(output_filename) 
Example 40
Project: hrt   Author: tansey   File: sim_predictors_importance.py    MIT License 5 votes vote down vote up
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        plt.xlabel('')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True) 
Example 41
Project: hrt   Author: tansey   File: sim_predictors_order.py    MIT License 5 votes vote down vote up
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        plt.xlabel('')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True) 
Example 42
Project: hrt   Author: tansey   File: sim_predictors_agg.py    MIT License 5 votes vote down vote up
def results_plot(tpr_vals, fdr_vals, r2_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        order = np.argsort([np.mean(r) if len(r) > 0 else 1 for r in r2_vals])
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for idx in order:
            t, f, r, n = tpr_vals[idx], fdr_vals[idx], r2_vals[idx], names[idx]
            # rates.extend(r)
            rates.extend(t)
            rates.extend(f)
            # labels.extend(['$\\mathbf{r^2}$']*len(r))
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.xlabel('', fontsize=18, weight='bold')
        # plt.ylabel('Power, FDR, and $\\mathbf{r^2}$', fontsize=18, weight='bold')
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True) 
Example 43
Project: enzynet   Author: shervinea   File: real_time.py    MIT License 5 votes vote down vote up
def __init__(self, max_entries=200, x_label=r'Epochs', y_label=r'Accuracy'):
        # TeX friendly
        plt.rc('text', usetex=True)
        plt.rc('font', family='serif')

        # Store
        self.fig, self.axes = plt.subplots()
        self.max_entries = max_entries

        # x-axis
        self.axis_x = deque(maxlen=max_entries)

        # Training accuracy
        self.axis_y_tr = deque(maxlen=max_entries)
        self.lineplot_tr, = self.axes.plot([], [], "ro-")

        # Validation accuracy
        self.axis_y_val = deque(maxlen=max_entries)
        self.lineplot_val, = self.axes.plot([], [], "bo-")

        # Autoscale
        self.axes.set_autoscaley_on(True)

        # Set label names
        self.axes.set_xlabel(x_label)
        self.axes.set_ylabel(y_label) 
Example 44
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, tables=None, psps=[None], params=None, rawdata=None,
                 latex=False, computed=None):
        if latex:
            mpl.rc('font', **{'family': 'serif', 'serif': ['Helvetica']})
            mpl.rc('text', usetex=True)
        general_utils.snep_plotting.Snep.__init__(self, params, rawdata,
                                                  computed=computed)
        self.tables = tables
        self.psps = psps
        # self.params = params
        # self.rawdata = rawdata
        # for k, v in params['sim'].items():
        # 	setattr(self, k, v)
        # for k, v in params['out'].items():
        # 	setattr(self, k, v)
        # for k, v in rawdata.items():
        # 	setattr(self, k, v)
        self.color_cycle_blue3 = general_utils.plotting.color_cycle_blue3
        # self.box_linspace = np.linspace(-self.radius, self.radius, 200)
        # self.time = np.arange(0, self.simulation_time + self.dt, self.dt)
        self.colors = {'exc': '#D7191C', 'inh': '#2C7BB6'}
        self.population_name = {'exc': r'excitatory', 'inh': 'inhibitory'}
        self.populations = ['exc', 'inh']
        # self.fig = plt.figure()
        self.cms = {'exc': mpl.cm.Reds, 'inh': mpl.cm.Blues}
        self.correlogram_of = 'rate_map'
        self.inner_square = False
        self.sophie_data = False

        if tables:
            self.computed_full = self.tables.get_computed(None) 
Example 45
Project: active-evaluation   Author: arunchaganty   File: plot.py    MIT License 5 votes vote down vote up
def do_correlation_table(args):
    with open(args.input) as f:
        data = load_jsonl(f)
    data = get_correlations(data)
    data = data[args.data_prompt]

    prompt = args.data_prompt
    metrics = sorted(data.keys())
    task = first(key for key, values in PROMPTS.items() if prompt in values)
    systems = SYSTEMS[task] + ["*"]

    X = np.array([[data[metric][system] for system in systems] for metric in metrics])

    plt.rc("font", size=16)
    plt.rc("text", usetex=False)
    #plt.rc("figure", figsize=(10,10))

    draw_matrix(X, with_values=True,
                x_labels=[LABELS.get(s, s) for s in systems],
                y_labels=[LABELS.get(m, m) for m in metrics],)

    plt.colorbar(label=r"Pearson ρ")
    plt.xlabel("Systems")
    plt.ylabel("Metrics")

    if args.with_title:
        task = first(key for key, values in PROMPTS.items() if prompt in values)
        plt.title(r"Correlations on {} using the {} prompt".format(
            LABELS.get(task, task),
            LABELS.get(prompt, prompt),
            ), fontsize=14)

    plt.tight_layout()
    plt.savefig(args.output) 
Example 46
Project: active-evaluation   Author: arunchaganty   File: plot.py    MIT License 5 votes vote down vote up
def do_data_efficiency_table(args):
    data = [json.loads(line) for line in open(args.input, "rt")]
    data = get_data_efficiencies(data)

    prompt = args.data_prompt
    metrics = sorted(data.keys())
    task = first(key for key, values in PROMPTS.items() if prompt in values)
    systems = SYSTEMS[task]

    X = np.array([[data[metric][prompt][system]**2 for system in systems] for metric in metrics])

    plt.rc("font", size=16)
    plt.rc("text", usetex=False)

    draw_matrix(X, with_values=True,
                x_labels=[LABELS.get(s, s) for s in systems],
                y_labels=[LABELS.get(m, m) for m in metrics],
                vmin=0.9, vmax=1.3)

    plt.colorbar(label="Data efficiency")
    plt.xlabel("Systems")
    plt.ylabel("Metrics")

    if args.with_title:
        plt.title(r"Data efficiencies on {} using the {} prompt".format(
            LABELS.get(task, task),
            LABELS.get(prompt, prompt),
            ), fontsize=14)


    plt.tight_layout()
    plt.savefig(args.output) 
Example 47
Project: Bayesian_Optimization_Material_design   Author: rajak7   File: predict_structure.py    GNU General Public License v3.0 5 votes vote down vote up
def plotbandstructure(XX,structure,YY1,YY2):
    fig = plt.figure(figsize=(7, 7))
    plt.rc('xtick', labelsize=20)
    plt.rc('ytick', labelsize=20)
    plt.rc('font', weight='bold')
    plt.plot(XX, YY1, 'b-', linewidth=3.5, label=u'HOMO')
    plt.plot(XX, YY2, 'r-', linewidth=3.5, label=u'LOMO')
    plt.title(structure, fontsize=20, fontweight='bold')
    plt.show()

#make polt of the CBM/VBM for the test set inside a folder Bandstructure 
Example 48
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_errorbar_with_prop_cycle():
    _cycle = cycler(ls=['--', ':'], marker=['s', 's'], mfc=['k', 'w'])
    plt.rc("axes", prop_cycle=_cycle)
    fig, ax = plt.subplots()
    ax.errorbar(x=[2, 4, 10], y=[3, 2, 4], yerr=0.5)
    ax.errorbar(x=[2, 4, 10], y=[6, 4, 2], yerr=0.5) 
Example 49
Project: ble5-nrf52-mac   Author: tomasero   File: test_spines.py    MIT License 5 votes vote down vote up
def test_spines_capstyle():
    # issue 2542
    plt.rc('axes', linewidth=20)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_xticks([])
    ax.set_yticks([]) 
Example 50
Project: chicago-crime   Author: thekingofkings   File: multi_view_prediction.py    MIT License 5 votes vote down vote up
def plot_hourly_evaluation(year):
    r = pickle.load(open("embeddings-{0}.pickle".format(year)))
    with open("../kdd16-eval-{0}.pickle".format(year)) as fin:
        kdd_mae = pickle.load(fin)
        kdd_mre = pickle.load(fin)
        
    mf_mre = r[0]
    mf_mae = r[3]
    line_mre = r[1]
    line_mae = r[4]
    dge_mre = r[2]
    dge_mae = r[5]
    
    start = 6
    
    plt.rc("axes", linewidth=2)
    plt.figure(figsize=(8,6))
    plt.plot(kdd_mre[start:], 'g--', lw=3)
    plt.plot(mf_mre[start:], "r:", lw=4)
    plt.plot(line_mre[start:], "y-.", lw=4)
    plt.plot(dge_mre[start:], 'b-', lw=3)
    
    plt.legend(["RAW", "MF", "LINE", "HDGE"], fontsize=20, loc='best') # bbox_to_anchor=(0.8, 0.4)) # 
    plt.xlabel("Hour in day", fontsize=20)
    plt.ylabel("$MRE$", fontsize=24)
    plt.tick_params(labelsize=18)
    plt.axis([0, 17, 0.22, 0.45])
    plt.gca().set_xticks([0,6,12,17])
    plt.gca().set_xticklabels(("6:00", "12:00", "18:00", "23:00"))
    plt.grid(b=True, axis="both", lw=1)
    plt.savefig("hourly-eval-{0}.pdf".format(year))