Exemplo n.º 1
0
def plotting(parsed_data):
    # figure plot
    fig, ax = plt.subplots()
    font = {'family' : 'Times New Roman',
            'weight' : 'normal',
            'size'   : 20}
    matplotlib.rc('font', **font)
    fig = matplotlib.pyplot.gcf()
    fig.gca().grid(True)

    fig.set_size_inches(10,5)   # figure size
    linewidth = 1               # line width
    plt.xlabel('(ms)')
    plt.ylabel('CDF')
    plt.title('Offload Latency Comparision')
    plt.xlim([0, 250])         # x-axis range

    for (label, line_style, x_list, y_list) in parsed_data:
        # if line_style.endswith("--"):
        #     plt.plot(x_list, y_list, line_style, label=label, linewidth=linewidth, dashes=(20,5))
        # else:
        #     if line_style.endswith("-."):
        #         plt.plot(x_list, y_list, line_style, label=label, linewidth=linewidth, dashes=(10,3,3,3))
        #     else:
        plt.plot(x_list, y_list, '-', color=line_style, label=label, linewidth=linewidth)
    plt.legend(loc='lower right', prop={'size':13})   # legend style
    plt.savefig('img/CDF.png', bbox_inches='tight')
Exemplo n.º 2
0
def show_cmaps(names):
    matplotlib.rc('text', usetex=False)
    a=np.outer(np.arange(0,1,0.01),np.ones(10))   # pseudo image data
    f=figure(figsize=(10,5))
    f.subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)
    # get list of all colormap names
    # this only obtains names of built-in colormaps:
    maps=[m for m in cm.datad if not m.endswith("_r")]
    # use undocumented cmap_d dictionary instead
    maps = [m for m in cm.cmap_d if not m.endswith("_r")]
    maps.sort()
    # determine number of subplots to make
    l=len(maps)+1
    if names is not None: l=len(names)  # assume all names are correct!
    # loop over maps and plot the selected ones
    i=0
    for m in maps:
        if names is None or m in names:
            i+=1
            ax = subplot(1,l,i)
            ax.axis("off")
            imshow(a,aspect='auto',cmap=cm.get_cmap(m),origin="lower")
            title(m,rotation=90,fontsize=10,verticalalignment='bottom')
#    savefig("colormaps.png",dpi=100,facecolor='gray')
    show()
Exemplo n.º 3
0
def main():
    parser = argparse.ArgumentParser(description="""Compute subset of users who rated at
                                     least 10 movies and plot fraction of users satisfied
                                     as a function of inventory size.""")
    parser.add_argument("infilename",
                        help="Read from this file.", type=open)
    args = parser.parse_args()

    ratings = read_inputs(args.infilename)
    ratings = ratings.drop("timestamp", axis=1)
    movie_rankings = find_movie_rankings(ratings)
    ratings = ratings.drop("rating", axis=1)
    user_rankings = find_user_rankings(ratings, movie_rankings)
    num_users = user_rankings.user_id.unique().size
    num_movies = movie_rankings.shape[0]
    user_rankings = clean_rankings(user_rankings)

    us_levels_100 = find_satisfaction(user_rankings, num_users, num_movies)
    us_levels_90 = find_satisfaction(user_rankings, num_users, num_movies, satisfaction_level=0.9)

    rc('text', usetex=True)
    plt.title('Percent of Users Satisfied vs Inventory Size in the MovieLens Dataset')
    plt.xlabel('Inventory Size')
    plt.ylabel('Percent of Users Satisfied')
    plt.plot(us_levels_100, 'b', label=r'$100\% \ satisfaction$')
    plt.plot(us_levels_90, 'r--', label=r'$90\% \ satisfaction$')
    plt.legend()
    d = datetime.datetime.now().isoformat()
    plt.savefig('user_satisfaction_%s.png' % d)
def plot_Q_by_year(log=False,show=False,save=False,filename=''):
    mpl.rc('lines',markersize=6)
    fig, (Q2012,Q2013,Q2014,Q2015)=plt.subplots(4)
    letter_subplots(fig,0.1,0.95,'top','right','k',font_size=10,font_weight='bold')
    
    for ax in fig.axes:
        ax.plot_date(LBJ['Q'].index,LBJ['Q'],ls='-',marker='None',c='k',label='Q FG3')
        #ax.plot(LBJstageDischarge.index,LBJstageDischarge['Q-AV(L/sec)'],ls='None',marker='o',color='k')
        ax.set_ylim(0,LBJ['Q'].max()+500)  
    
    Q2014.axvline(study_start), Q2015.axvline(study_end)  
    Q2012.set_xlim(start2012,stop2012),Q2013.set_xlim(start2013,stop2013)
    Q2014.set_xlim(start2014,stop2014),Q2015.set_xlim(start2015,stop2015)
    Q2012.legend(loc='best')
    Q2013.set_ylabel('Discharge (Q) L/sec')
    #Q2012.set_title("Discharge (Q) L/sec at the Upstream and Downstream Sites, Faga'alu")
    
    for ax in fig.axes:
        ax.locator_params(nbins=6,axis='y')
        ax.xaxis.set_major_locator(mpl.dates.MonthLocator(interval=2))
        ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('%b %Y'))
        
    plt.tight_layout(pad=0.1)
    logaxes(log,fig)
    show_plot(show,fig)
    savefig(save,filename)
    return
Exemplo n.º 5
0
def plot_monthly_average_consumption(mpc, country_list, ylabel='normalized', title='', kind='bar', linestyle='-', color='mbygcr', marker='o', linewidth=4.0, fontsize=16, legend=True):
    """
    This function plots the yearly data from a monthlypowerconsumptions object
    @param df: monthlypowerconsumptions object
    @param country_list: country names to add on the title of the plot
    @param ylabel: label for y axis
    @param title: graphic title
    @param kind: graphic type ex: bar or line
    @param linestyle: lines style
    @param color: color to use
    @param marker: shape of point on a line
    @param linewidth: line width
    @param fontsize: font size
    @return: n/a
    """

    # Plotting
    font = {'family' : 'normal',
            'weight' : 'bold',
            'size'   : 12}

    matplotlib.rc('font', **font)

    df = mpc.data_normalization(year=False)
    df = df.groupby('country').mean()
    del df['year']
    del df['Sum']
    df = df.T
    plot_several_countries(df[country_list], ylabel, title, kind=kind, linestyle=linestyle, color=color, marker=marker, linewidth=linewidth, fontsize=fontsize, legend=legend)
Exemplo n.º 6
0
def plot_color_gradients(gradients, names):
    # For pretty latex fonts (commented out, because it does not work on some machines)
    #rc('text', usetex=True)
    #rc('font', family='serif', serif=['Times'], size=10)
    rc('legend', fontsize=10)

    column_width_pt = 400         # Show in latex using \the\linewidth
    pt_per_inch = 72
    size = column_width_pt / pt_per_inch

    fig, axes = plt.subplots(nrows=len(gradients), sharex=True, figsize=(size, 0.75 * size))
    fig.subplots_adjust(top=1.00, bottom=0.05, left=0.25, right=0.95)


    for ax, gradient, name in zip(axes, gradients, names):
        # Create image with two lines and draw gradient on it
        img = np.zeros((2, 1024, 3))
        for i, v in enumerate(np.linspace(0, 1, 1024)):
            img[:, i] = gradient(v) #wywołujemy sobie każdą funkcje z v

        im = ax.imshow(img, aspect='auto')
        im.set_extent([0, 1, 0, 1])
        ax.yaxis.set_visible(False)

        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.25
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, name, va='center', ha='left', fontsize=10)

    fig.savefig('my-gradients.pdf')
Exemplo n.º 7
0
def test_rcparams():
    mpl.rc('text', usetex=False)
    mpl.rc('lines', linewidth=22)

    usetex = mpl.rcParams['text.usetex']
    linewidth = mpl.rcParams['lines.linewidth']
    fname = os.path.join(os.path.dirname(__file__), 'test_rcparams.rc')

    # test context given dictionary
    with mpl.rc_context(rc={'text.usetex': not usetex}):
        assert mpl.rcParams['text.usetex'] == (not usetex)
    assert mpl.rcParams['text.usetex'] == usetex

    # test context given filename (mpl.rc sets linewidth to 33)
    with mpl.rc_context(fname=fname):
        assert mpl.rcParams['lines.linewidth'] == 33
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test context given filename and dictionary
    with mpl.rc_context(fname=fname, rc={'lines.linewidth': 44}):
        assert mpl.rcParams['lines.linewidth'] == 44
    assert mpl.rcParams['lines.linewidth'] == linewidth

    # test rc_file
    mpl.rc_file(fname)
    assert mpl.rcParams['lines.linewidth'] == 33
Exemplo n.º 8
0
def show_cccmacms():
    # plot the colormaps as the demo example
    # http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps

    register_cccmacms()
    names = list_cccmacms()

    # COPIED BELOW CODE
    # base code from http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps
    matplotlib.rc("text", usetex=False)
    a = np.outer(np.arange(0, 1, 0.01), np.ones(10))  # pseudo image data
    f = plt.figure(figsize=(7, 9))
    f.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)
    # get list of all colormap names
    # this only obtains names of built-in colormaps:
    maps = [m for m in cm.datad if not m.endswith("_r")]
    # use undocumented cmap_d dictionary instead
    maps = [m for m in cm.cmap_d if not m.endswith("_r")]
    maps.sort()
    # determine number of subplots to make
    l = len(maps) + 1
    if names is not None:
        l = len(names)  # assume all names are correct!
    # loop over maps and plot the selected ones
    i = 0
    for m in maps:
        if names is None or m in names:
            i += 1
            ax = plt.subplot(1, l, i)
            ax.axis("off")
            plt.imshow(a, aspect="auto", cmap=cm.get_cmap(m), origin="lower")
            plt.title(m, rotation=90, fontsize=10, verticalalignment="bottom")
Exemplo n.º 9
0
    def __init__(self, parent, messenger=None,
                 size=(6.00,3.70), dpi=96, **kwds):

        self.is_macosx = False
        if os.name == 'posix':
            if os.uname()[0] == 'Darwin': self.is_macosx = True

        matplotlib.rc('axes', axisbelow=True)
        matplotlib.rc('lines', linewidth=2)
        matplotlib.rc('xtick',  labelsize=11, color='k')
        matplotlib.rc('ytick',  labelsize=11, color='k')
        matplotlib.rc('grid',  linewidth=0.5, linestyle='-')

        self.messenger = messenger
        if (messenger is None): self.messenger = self.__def_messenger

        self.conf = ImageConfig()
        self.cursor_mode='cursor'

        self.launch_dir  = os.getcwd()
        self.mouse_uptime= time.time()
        self.last_event_button = None

        self.view_lim  = (None,None,None,None)
        self.zoom_lims = [self.view_lim]
        self.old_zoomdc= (None,(0,0),(0,0))

        self.parent    = parent

        self._yfmt = '%.4f'
        self._xfmt = '%.4f'

        self.figsize = size
        self.dpi     = dpi
        self.__BuildPanel(**kwds)
Exemplo n.º 10
0
    def SimpleAlphaVSTime(self):
        '''
        Step through every pair of points in a lightcurve to calculate a very
        rough measurement of alpha based on the slope of those two points.
        '''
        # set font
        rc('font', family='Times New Roman')
        
        fig=plt.figure()
        ax=fig.add_axes([0.1,0.1,0.8,0.8])
        ax.semilogx()

        for key, ob in self.obsdict.iteritems():
            upperinds = np.array(ob.isupperlist)
            detectinds = np.array([not a for a in ob.isupperlist])
        
            tmidarr = np.array(ob.tmidlist)[detectinds]
            magarr = np.array(ob.maglist)[detectinds]
            if detectinds.any(): # only plot here if we have at least one detection
                ind = 0
                # loop through each pair of mags 
                while ind < len(magarr) - 1:
                    mag1 = magarr[ind]
                    mag2 = magarr[ind+1]
                    t1 = tmidarr[ind]
                    t2 = tmidarr[ind+1]
                    tmid = (t1 + t2)/2.0
                    alpha = mag2alpha(mag_1=mag1,mag_2=mag2,t_1=t1,t_2=t2)
                    ax.plot(tmid,alpha, color=ob.color, marker=ob.marker)
                    ind += 1
        
        ax.set_ylabel(r'$\alpha$',size=16)
        ax.set_xlabel(r'$t_{mid}$ (s)',size=16)                
        fig.show()
Exemplo n.º 11
0
    def show_plate():

        import matplotlib.pyplot as plt
        from matplotlib import rc
        import daft
        plt.rcParams['figure.figsize'] = 14, 8
        rc("font", family="serif", size=12)
        rc("text", usetex=False)

        pgm = daft.PGM(shape=[2.5, 3.5], origin=[0, 0], grid_unit=4,
                        label_params={'fontsize':18}, observed_style='shaded')

        pgm.add_node(daft.Node("lambda", r"$\lambda$", 1, 2.4, scale=2))
        pgm.add_node(daft.Node("alpha_0", r"$\alpha_0$", 0.8, 3, scale=2,
                                fixed=True, offset=(0,10)))
        pgm.add_node(daft.Node("lambda_0", r"$\lambda_0$", 1.2, 3, scale=2,
                                fixed=True, offset=(0,6)))
        pgm.add_node(daft.Node("y", r"$y_i$", 1, 1.4, scale=2, observed=True))
        pgm.add_plate(daft.Plate([0.5, 0.7, 1, 1.3], label=r"$i \in 1:N$", 
                                    shift=-0.1))

        pgm.add_edge("alpha_0", "lambda")
        pgm.add_edge("lambda_0", "lambda")
        pgm.add_edge("lambda", "y")

        pgm.render()
        plt.show()
Exemplo n.º 12
0
def plot_bias(bias_list, fpath):
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns

    sys.stderr.write("saving to %s\n" % fpath)
    p = sns.color_palette("deep", desat=.8)
    c1, c2 = p[0], p[-1]
    c1, c2 = sns.color_palette("Set1", 2)

    mpl.rc("figure", figsize=(8, 4))
    f, ax1 = plt.subplots(1)

    xs = [int(x['base']) for x in bias_list]

    ax1.plot(xs, [100 * float(x['read_1']) for x in bias_list], c=c1,
             label="read 1")
    ax1.plot(xs, [100 * float(x['read_2']) for x in bias_list], c=c2,
             label="read 2")
    ax1.axvline(x=4, c="#aaaaaa", alpha=0.8, linewidth=3, zorder=-1)
    ax1.axvline(x=max(xs) - 4, c="#aaaaaa", alpha=0.8, linewidth=3, zorder=-1)

    ax1.legend(loc='upper center')
    ax1.set_xlim(min(xs), max(xs))
    ax1.set_ylabel('mean CG % methylation')
    ax1.set_xlabel('position along read')
    ax1.set_title('Methylation Bias Plot (vertical lines at 4 bases from end)')
    ax1.grid('off')

    f.tight_layout()
    f.savefig(fpath)
Exemplo n.º 13
0
def plot_config(filetype='png'):
    import matplotlib
    # matplotlib.use('pdf')
    import matplotlib.pyplot
    params = {
        'text.usetex': True,
        'figure.dpi' : 300,
        'savefig.dpi' : 300,
        'savefig.format' : filetype,
        # 'axes.labelsize': 8, # fontsize for x and y labels (was 10)
        # 'axes.titlesize': 8,
        # 'text.fontsize': 8, # was 10
        # 'legend.fontsize': 8, # was 10
        # 'xtick.labelsize': 8,
        # 'ytick.labelsize': 8,
        # 'figure.figsize': [fig_width,fig_height],
        'font.family': 'serif',
        'text.latex.preamble': [r'\usepackage[]{siunitx}'
                                r'\usepackage[]{mhchem}'],
    }
    matplotlib.rcParams.update(params)
    matplotlib.style.use('bmh')
    matplotlib.style.use('seaborn-paper')
    # matplotlib.style.use('seaborn-dark-palette')

    matplotlib.rc('axes', facecolor='white')
    matplotlib.rc('grid', linestyle='-', alpha=0.0)
Exemplo n.º 14
0
def create_figures(data):
    import numpy as np
    print "# Creating figure ..."
    # prepare matplotlib
    import matplotlib
    matplotlib.rc("font",**{"family":"sans-serif"})
    matplotlib.rcParams.update({'font.size': 14})
    matplotlib.rc("text", usetex=True)
    matplotlib.use("PDF")
    import matplotlib.pyplot as plt

    # KSP
    plt.figure(1)
    n, bins, patches = plt.hist(data[:, 1], bins = 50, fc = "k", ec = "w")
    plt.xticks(range(300, 1001, 100), range(300, 1001, 100))
    plt.yticks(range(0, 17, 2), range(0, 17, 2))
    plt.xlabel("Model years")
    plt.ylabel("Occurrence")
    plt.savefig("parameterrange-ksp", bbox_inches = "tight")

    # SNES
    plt.figure(2)
    n, bins, patches = plt.hist(data[:, 0], bins = 50, fc = "k", ec = "w")
    plt.xticks(range(5, 46, 5), range(5, 46, 5))
    plt.yticks(range(0, 15, 2), range(0, 15, 2))
    plt.xlabel("Newton steps")
    plt.ylabel("Occurrence")
    plt.savefig("parameterrange-snes", bbox_inches = "tight")
Exemplo n.º 15
0
def _test_determinism_save(filename, usetex):
    # This function is mostly copy&paste from "def test_visibility"
    # To require no GUI, we use Figure and FigureCanvasSVG
    # instead of plt.figure and fig.savefig
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_svg import FigureCanvasSVG
    from matplotlib import rc
    rc('svg', hashsalt='asdf')
    rc('text', usetex=usetex)

    fig = Figure()
    ax = fig.add_subplot(111)

    x = np.linspace(0, 4 * np.pi, 50)
    y = np.sin(x)
    yerr = np.ones_like(y)

    a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
    for artist in b:
        artist.set_visible(False)
    ax.set_title('A string $1+2+\\sigma$')
    ax.set_xlabel('A string $1+2+\\sigma$')
    ax.set_ylabel('A string $1+2+\\sigma$')

    FigureCanvasSVG(fig).print_svg(filename)
Exemplo n.º 16
0
 def plot_sleipner_thick_contact(self, years, gwc = False, sim_title = ''):
     if gwc == True:
         tc_str = 'contact'
     else:
         tc_str = 'thickness'
     yr_indices = self.get_plan_year_indices(years)
     size = 14
     font = {'size' : size}
     matplotlib.rc('font', **font)
     fig = plt.figure(figsize=(10.0, 2.5), dpi = 960)
     middle = len(years) * 10
     pos = 100 + middle
     for n in range(len(yr_indices)):
         pos +=1
         ax = fig.add_subplot(pos)
         xf = []
         yf = []
         kf = []
         for i in range(self.nx):
             tempx = []
             tempy = []
             tempk = []
             for j in range(self.ny):
                 x = self.x[(i, j, 0)]
                 y = self.y[(i, j, 0)]
                 tn = yr_indices[n]
                 thick, contact = self.get_thick_contact(i, j, tn)
                 tempx.append(x)
                 tempy.append(y)
                 if gwc == True:
                     tempk.append(contact)
                 else:
                     tempk.append(thick)
             xf.append(tempx)
             yf.append(tempy)
             kf.append(tempk)
         xp = np.asarray(xf)
         yp = np.asarray(yf)
         kp = np.asarray(kf)
         N = 10
         contour_label = False
         ax_label = False
         c = ax.contourf(xp, yp, kp, N)
         plt.tick_params(which='major', length=3, color = 'w')
         if n == len(years) - 1:
             fig.subplots_adjust(right=0.84)
             cb_axes = fig.add_axes([0.85, 0.15, 0.05, 0.7])
             plt.tick_params(which='major', length=3, color = 'k')
             cb = fig.colorbar(c, cax = cb_axes, format = '%.2f')
             cb.set_ticks(np.linspace(np.amin(kp), np.amax(kp), N))
             cb.set_label(tc_str + ': [m]')
         if n != 0:
             ax.set_yticklabels([])
         ax.set_xticklabels([])
         ax.set_title(str(years[n]))
         ax.axis([0, 3000, 0, 6000])
         ax.xaxis.set_ticks(np.arange(0,3500,1000))
     plt.savefig(sim_title + '_' +  tc_str + '.pdf', fmt = 'pdf')
     plt.clf()
     return 0
Exemplo n.º 17
0
def subplot_modes(modes):
    """
    modes is a list of lists (one for each natural frequency)
    each sublist contains 3-comp tuples with (label, freq, mode)
    """
    n = len(modes)
    print "\nPloting {0} first modes:".format(n)

    # initiate plot
    fig, axarr = plt.subplots(n, sharex=True)

    rc('font', **{'family': 'sans-serif',
                  'sans-serif': ['Computer Modern Roman']})
    # rc('text', usetex=True)
    legend_kwargs = {'loc': 'center left', 'bbox_to_anchor': (1, 0.5)}
    for i, mode_container in enumerate(modes):
        print "\nMode {0}".format(i+1)

        legend = map(lambda x: " ".join((x[0], "(f={0:.2f} Hz)".format(x[1]))),
                     mode_container)
        modes_i = map(lambda x: x[2], mode_container)

        for j, mode in enumerate(modes_i):
            x = np.linspace(0, L, len(mode))
            axarr[i].plot(x, mode, style_gen(j, j))
        axarr[i].legend(legend, **legend_kwargs)
        axarr[i].grid()

    axarr[n-1].set_xlabel(r"Length of the beam ($y$ axis) in meters")
    axarr[n/2].set_ylabel(r"Normalized deflection")
    plt.subplots_adjust(right=0.6)
Exemplo n.º 18
0
 def plotLearning(self, filename):
     """ Plot evolution of weights throughout the training process """
     if not self.trackLearning:
         raise Exception("cannot plot, no tracking data")
     font = {'size' : 10}
     matplotlib.rc('font', **font)
     plt.figure()
     # create two plots in a single image
     # top half for error
     plt.subplot(211)
     plt.title("Evolution of Error and Weights")
     plt.plot(self.errorHistoryX, self.errorHistoryY, label='Error')
     plt.ylabel('prediction error')
     plt.grid(True)
     plt.ylim(bottom=0.0, top=1.0)
     # bottom half for weights
     plt.subplot(212)
     for layerName in self.preceptronLayers.keys():
         layer = self.preceptronLayers[layerName]
         plt.plot(self.errorHistoryX, layer.weightsHistory, label='{0}'.format(layerName))
     plt.ylabel('root sum square of weights')
     plt.grid(True)
     plt.legend(loc="best", prop={'size': 6})
     plt.xlabel('epochs')
     plt.savefig(filename)
Exemplo n.º 19
0
 def __init__(self, discrete_bool, co2_data):
     # matplot steup
     mpl.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
     mpl.rcParams['text.usetex'] = True
     mpl.rcParams['xtick.labelsize'] = 30
     mpl.rcParams['xtick.color'] = "white"
     mpl.rcParams['ytick.labelsize'] = 12
     mpl.rcParams['axes.edgecolor'] = 'white'
     mpl.rcParams['axes.linewidth'] = 0.
     mpl.rcParams['axes.labelcolor'] = 'white'
     
     # is the figure discrete or not?
     if discrete_bool:
         # create figure
         self.n = len(co2_data[:,0])
         self.fig = plt.figure(figsize = (4*self.n, 3),dpi = 80)
         
         # assign the data, is array
         self.data = co2_data
         
     # for continuous
     else:
         self.fig = plt.figure(figsize=(10, 1.8), dpi = 80)
         self.min_x = co2_data[0]
         self.max_x = co2_data[1]
Exemplo n.º 20
0
def plot_runtime_results(results):
    plt.rcParams["figure.figsize"] = 7,7
    plt.rcParams["font.size"] = 22
    matplotlib.rc("xtick", labelsize=24)
    matplotlib.rc("ytick", labelsize=24)

    params = {"text.fontsize" : 32,
              "font.size" : 32,
              "legend.fontsize" : 30,
              "axes.labelsize" : 32,
              "text.usetex" : False
              }
    plt.rcParams.update(params)
    
    #plt.semilogx(results[:,0], results[:,3], 'r-x', lw=3)
    #plt.semilogx(results[:,0], results[:,1], 'g-D', lw=3)
    #plt.semilogx(results[:,0], results[:,2], 'b-s', lw=3)

    plt.plot(results[:,0], results[:,3], 'r-x', lw=3, ms=10)
    plt.plot(results[:,0], results[:,1], 'g-D', lw=3, ms=10)
    plt.plot(results[:,0], results[:,2], 'b-s', lw=3, ms=10)

    plt.legend(["Chain", "Tree", "FFT Tree"], loc="upper left")
    plt.xticks([1e5, 2e5, 3e5])
    plt.yticks([0, 60, 120, 180])

    plt.xlabel("Problem Size")
    plt.ylabel("Runtime (sec)")
    return results
def Power_Spectrum_Plot_Construction(Gravity_obj,file_loc_save="Report/",file_loc_load="Output/Power_Spectrum_data/"):
    rc('text',usetex=True)    

    Setting_number = Gravity_obj.output.Power_Spectrum_Setting_number

    (t , r , Ricci) = loadtxt(file_loc_load+Gravity_obj.output.Power_Spectrum_file_name,dtype='float',comments='#',unpack=True)

    for i in range(Gravity_obj.output.Power_Spectrum_points):
       t_local     = zeros(len(t)/Gravity_obj.output.Power_Spectrum_points)
       Ricci_local = zeros(len(t)/Gravity_obj.output.Power_Spectrum_points)

       for j in range(len(t)/Gravity_obj.output.Power_Spectrum_points):
          t_local[j]     = t[j*Gravity_obj.output.Power_Spectrum_points+i]
          Ricci_local[j] = Ricci[j*Gravity_obj.output.Power_Spectrum_points+i]

       (k,pk) = Power_Spectrum_1D_Cal(t_local,Ricci_local,Setting_number)       
       clf()
       loglog(k,pk/pk[1])

       coef   = Linear_Fit_Line(log(k[len(k)/10:len(k)-1]),log(pk[len(k)/10:len(k)-1]/pk[1]))
       Gravity_obj.field.Power_Spec_n.append(coef[0])
       loglog(k,coef[1]*k**coef[0],label=r'$\propto k^{ %0.2f }$'%Gravity_obj.field.Power_Spec_n[i])

       legend()
       xlabel(r'$\omega$',fontsize = 20)
       ylabel(r'$P(\omega)$',fontsize = 20)
       title(r'$r = '+str(r[i])+r'$',fontsize = 20)
       fdir  = file_loc_save
       fname = 'Power_Spectrum%02d.pdf'%(i+1)
       print 'n = ', Gravity_obj.field.Power_Spec_n[i]
       print 'Saving plot', fname
       savefig(fdir+fname)

    rc('text',usetex=False)  
Exemplo n.º 22
0
def config_mpl():
    mpl.rc('lines', linewidth=1.5)
    mpl.rc('font', family='Times New Roman', size=16, monospace='Courier New')
    mpl.rc('legend', fontsize='small', fancybox=False,
           labelspacing=0.1, borderpad=0.1, borderaxespad=0.2)
    mpl.rc('figure', figsize=(12, 10))
    mpl.rc('savefig', dpi=120)
Exemplo n.º 23
0
 def __get_plot_dict(plot_style):
     """Define plot styles."""
     plot_dict = {
         Data.condor_running: ("Jobs running", "#b8c9ec"),  # light blue
         Data.condor_idle: ("Jobs available", "#fdbe81"),  # light orange
         Data.vm_requested: ("Slots requested", "#fb8a1c"),  # orange
         Data.vm_running: ("Slots available", "#2c7bb6"),  # blue
         Data.vm_draining: ("Slots draining", "#7f69db"),  # light blue
     }
     font = {"family": "sans", "size": 20}
     matplotlib.rc("font", **font)
     matplotlib.rcParams['pdf.fonttype'] = 42
     matplotlib.rcParams['ps.fonttype'] = 42
     if plot_style == "slide":
         matplotlib.rcParams["figure.figsize"] = 18, 8
         matplotlib.rcParams["svg.fonttype"] = "none"
         matplotlib.rcParams["path.simplify"] = True
         matplotlib.rcParams["path.simplify_threshold"] = 0.5
         matplotlib.rcParams["font.sans-serif"] = "Linux Biolinum O"
         matplotlib.rcParams["font.family"] = "sans-serif"
         matplotlib.rcParams["figure.dpi"] = 300
     elif plot_style == "screen":
         pass
     else:
         raise ValueError("Plotting style unknown!")
     return plot_dict
Exemplo n.º 24
0
def plotAvgError(p1_win, p1_var,
                 p2_all_win, p2_all_var,
                 p2_day_win, p2_day_var, y_max=8):
    matplotlib.rc('font', size=18)
    width = 2
    index = np.arange(0, 7 * width * len(budget_cnts), width * 7)
    fig, ax = plt.subplots()
    rect1 = ax.bar(index, p1_win, width, color='b', hatch='/')
    rect2 = ax.bar(index + width, p1_var, width, color='r', hatch='\\')
    rect3 = ax.bar(index + width*2, p2_all_win, width, color='g', hatch='//')
    rect4 = ax.bar(index + width*3, p2_all_var, width, color='c', hatch='\\')
    rect5 = ax.bar(index + width*4, p2_day_win, width, color='m', hatch='x')
    rect6 = ax.bar(index + width*5, p2_day_var, width, color='y', hatch='//')
    ax.set_xlim([-3, 7 * width * (len(budget_cnts) + 0.1)])
    ax.set_ylim([0, y_max])
    ax.set_ylabel('Mean Absolute Error')
    ax.set_xlabel('Budget Count')
    ax.set_xticks(index + width * 2.5)
    ax.set_xticklabels(('0', '5', '10', '20', '25'))
    ax.legend((rect1[0], rect2[0], rect3[0], rect4[0], rect5[0], rect6[0]),
              ('Phase 1 Window', 'Phase 1 Variance',
               'Phase 2 H-Window', 'Phase 2 H-Variance',
               'Phase 2 D-Window', 'Phase 2 D-Variance'),
              ncol=2, fontsize=15)
    plt.grid()
    plt.savefig('%s_err.eps' % topic, format='eps',
                bbox_inches='tight')
Exemplo n.º 25
0
def show_cmaps(names=None):
    """display all colormaps included in the names list. If names is None, all
defined colormaps will be shown."""
    # base code from http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps
    matplotlib.rc("text", usetex=False)
    a = np.outer(np.arange(0, 1, 0.01), np.ones(10))  # pseudo image data
    f = plt.figure(figsize=(10, 5))
    f.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)
    # get list of all colormap names
    # this only obtains names of built-in colormaps:
    maps = [m for m in cm.datad if not m.endswith("_r")]
    # use undocumented cmap_d dictionary instead
    maps = [m for m in cm.cmap_d if not m.endswith("_r")]
    maps.sort()
    # determine number of subplots to make
    l = len(maps) + 1
    if names is not None:
        l = len(names)  # assume all names are correct!
    # loop over maps and plot the selected ones
    i = 0
    for m in maps:
        if names is None or m in names:
            i += 1
            ax = plt.subplot(1, l, i)
            ax.axis("off")
            plt.imshow(a, aspect="auto", cmap=cm.get_cmap(m), origin="lower")
            plt.title(m, rotation=90, fontsize=10, verticalalignment="bottom")
    plt.savefig("colormaps.png", dpi=100, facecolor="gray")
Exemplo n.º 26
0
    def __init__(self, parent, sz = None):
        self._canvas_options = options.PlotCanvasOptions()
        matplotlib.rc('font', **self.canvas_options.fontdict)
        
        super(PlotCanvas, self).__init__(parent, wx.ID_ANY, style=wx.RAISED_BORDER)
        if not sz:
            self.delegate = wxagg.FigureCanvasWxAgg(self, wx.ID_ANY, plt.Figure(facecolor=(0.9,0.9,0.9)))
        else:
            self.delegate = wxagg.FigureCanvasWxAgg(self, wx.ID_ANY, plt.Figure(facecolor=(0.9, 0.9, 0.9), figsize=sz))

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.delegate, 1, wx.EXPAND)

        self.plot = self.delegate.figure.add_axes([0.1,0.1,0.8,0.8])
        self.pointsets = []

        self.delegate.figure.canvas.mpl_connect('pick_event', self.on_pick)
        self.delegate.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
        # self.figure.canvas.mpl_connect('motion_notify_event',self.on_motion)
        self.annotations = {}
        # used to index into when there is a pick event
        self.picking_table = {}
        self.dist_point = None

        self.SetSizerAndFit(sizer)
Exemplo n.º 27
0
    def update_graph(self):
        self.plot.clear()
        self.picking_table = {}

        iattrs = set()
        dattrs = set()
        
        matplotlib.rc('font', **self.canvas_options.fontdict)

        # for now, plot everything on the same axis

        error_bars = self.canvas_options.show_error_bars

        for points, opts in self.pointsets:
            if not opts.is_graphed:
                continue
            points = self.canvas_options.modify_pointset(self,points)
            self.picking_table[points.label] = points
            opts.plot_with(self, points, self.plot, error_bars)

            iattrs.add(points.independent_var_name)
            dattrs.add(points.variable_name)

        if self.canvas_options.show_axes_labels:
            self.plot.set_xlabel(", ".join([i or "" for i in iattrs]), 
                                 fontdict=self.canvas_options.fontdict)
            self.plot.set_ylabel(", ".join([d or "" for d in dattrs]), 
                                 fontdict=self.canvas_options.fontdict)

        self.canvas_options.plot_with(self, self.plot)
        self.draw()
Exemplo n.º 28
0
 def barplot(self, filename='', idx=None):
     """
     Plot a generic barplot using just the yVars.
     idx is the index of the each y-variable to be plotted. if not given, the last value will be used
     """
     import numpy
     mpl.rc('font',family='sans-serif')
     
     fig = plt.figure()
     ax = fig.add_subplot(111)
     
     position = numpy.arange(len(self.yVar),0,-1)
     # Reverse in order to go front top to bottom
     if not idx:
         idx = -1
     ax.barh(position, numpy.array([y.data[idx] for y in self.yVar]), align='center', alpha=0.5)
     plt.yticks(position, [y.label for y in self.yVar])
     
     # If any labels or titles are explicitly specified, write them
     if self.xlabel:
         plt.xlabel(self.xlabel)
         
     if self.ylabel:
         plt.ylabel(self.ylabel)
         
     if self.title:
         plt.title(self.title)
         
     plt.axis('tight')
     fig.savefig(filename, bbox_inches='tight')
Exemplo n.º 29
0
def plotBottleneck(maxGen=None,obs=False,mean=True,color='blue'):
    exit()

    def plotOne(df, ax, method):
        m=df.mean(1)
        s=df.std(1)
        # plt.locator_params(nbins=4);
        m.plot(ax=ax, legend=False, linewidth=3, color=color)
        x=m.index.values
        m=m.values;s=s.values
        ax.fill_between(x, m - 2 * s, m + 2 * s, color=color, alpha=0.3)
        ax.set_ylabel(method.strip())
        ax.set_ylim([-0.1, ax.get_ylim()[1]])

        pplt.setSize(ax)

    dfn = \
        pd.read_pickle(path + 'nu{}.s{}.df'.format(0.005, 0.0))
    fig, ax = plt.subplots(3, 1, sharex=True, figsize=(4, 3), dpi=300)
    plotOne(dfn['tajimaD'], ax[0], "Tajima's $D$");
    plt.xlabel('Generations')
    plotOne(dfn['HAF'], ax[1], "Fay Wu's $H$");
    plt.xlabel('Generations')
    plotOne(dfn['SFSelect'], ax[2], 'SFSelect');
    plt.xlabel('Generations')
    plt.gcf().subplots_adjust(bottom=0.25)
    mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']});
    mpl.rc('text', usetex=True)
    pplt.savefig('bottleneck', 300)
    plt.show()
Exemplo n.º 30
0
Arquivo: LD.py Projeto: airanmehr/bio
def plotLDDecaySelection3d(ax, sweep=False):
    import pylab as plt; import matplotlib as mpl;mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size':16}) ;    mpl.rc('text', usetex=True)

    def neutral(ld0, t, d, r=2 * 1e-8):
        if abs(d) <= 5e3:
            d = np.sign(d) * 5e3
        if d == 0:
            d = 5e3
        return ((np.exp(-2 * r * t * abs(d)))) * ld0

    t = np.arange(0, 200 + 1., 2)
    L=1e6+1
    pos=500000
    r=2*1e-8
    ld0 = 0.5
    s = 0.05
    nu0 = 0.1
    positions=np.arange(0,L,1000)
    dist=(positions - pos)
    T, D = np.meshgrid(t, dist)
    if not sweep:
        zs = np.array([neutral(ld0, t, d) for t, d in zip(np.ravel(T), np.ravel(D))])
    else:
        zs = np.array([LD(t, ld0, s, nu0, r, abs(d), 0) for t, d in zip(np.ravel(T), np.ravel(D))])
    Z = zs.reshape(T.shape)
    ax.plot_surface(T, D, Z,cmap=mpl.cm.autumn)
    ax.set_xlabel('Generations')
    ax.set_ylabel('Position')
    plt.yticks(plt.yticks()[0][1:-1],map(lambda x:'{:.0f}K'.format((pos+(x))/1000),plt.yticks()[0][1:-1]))
    plt.ylim([-500000,500000])
    ax.set_zlabel(r"$|\rho_t|$")
    pplt.setSize(plt.gca(), fontsize=6)
    plt.axis('tight');
Exemplo n.º 31
0
      'xtick.major.pad'      : 25,      # distance to major tick label in points
      'xtick.minor.pad'      : 25,      # distance to the minor tick label in points
      'ytick.major.pad'      : 8,     # distance to major tick label in points
      'ytick.minor.pad'      : 8,     # distance to the minor tick label in points
      
      'xtick.labelsize': 16,
      'ytick.labelsize': 16,

      'figure.figsize': [8,8],
      'figure.dpi': 800,
      # 'text.usetex': True,
      'axes.unicode_minus': True,
      'ps.usedistiller' : 'xpdf'
      }     
rc('font',**{'family':'serif','serif':['Helvetica']})

fig = plt.figure(figsize=(8,8))
ax = fig.gca(projection='3d')


#kx, ky = Read_kpoints_for_3Dband('KPOINTS')

#print len(kx), len(ky)

#EIGEN_array = Read_eigenvalue_for_3Dband('EIGENVAL',-2.1097)


# Make data.
#nx, ny = (80, 80)
#x = np.linspace(-0.16, 0.16, nx)
#=============================================================================#
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
import easyfit as ef
import easyfy as ez
import colormaps as cmaps
from scipy import integrate
from scipy.misc import comb
import os
import matplotlib.gridspec as gridspec

#=============================================================================#
#                           Setup  Plot Settings
#=============================================================================#
mpl.rc('font', **{'sans-serif' : 'Arial','family' : 'serif'})
mpl.rcParams['legend.fancybox'] = True
mpl.rcParams['legend.shadow'] = False
mpl.rcParams['figure.dpi'] = 100
mpl.rcParams['ytick.major.pad'] = 5
mpl.rcParams['xtick.major.pad'] = 5
mpl.rcParams['axes.formatter.limits'] = (-3,3)

plt.rcParams['pdf.fonttype'] = 42
plt.rc('font', **{'size':10})
legendFS = 10
textFS = 9
bgColor = 'w'
eColor='k'
colors = ez.colors()
    # print(outproj)
    # print("\n\n")

    # cmap = colors.ListedColormap(['white', '#1A7DD1'])

    return [m, xx, yy, stack]



################
# Main program #
################

font = {'family' : 'sans-serif',
        'size'   : 18}
matplotlib.rc('font', **font)

# writer = animation.writers['imagemagick']
writer = animation.writers['ffmpeg']
# writer = writer(fps=2, metadata=dict(artist='Me'), bitrate=2400)

h_in_inches = 12
w_in_inches = 9

fig = plt.figure(tight_layout=True, figsize=(h_in_inches, w_in_inches))
# fig.set_size_inches(h_in_inches, w_in_inches, True)

mng = plt.get_current_fig_manager()
# mng.resize(*mng.window.maxsize())
mng.full_screen_toggle()
Exemplo n.º 34
0
from hawc_hal import HAL, HealpixConeROI, HealpixMapROI
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('Agg')
mpl.rc("font", family="serif", size=14)

import warnings

from threeML.plugin_prototype import PluginPrototype
from astromodels.core.sky_direction import SkyDirection
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True

# This disable momentarily the printing of warnings, which you might get
# if you don't have the Fermi ST or other software installed
with warnings.catch_warnings():

    warnings.simplefilter("ignore")

    from threeML import *

#Load the data and detector response
maptree = "maptree.hd5"
response = "response.hd5"

#Spectral description
spectrum = Cutoff_powerlaw()
shape = Gaussian_on_sphere()

source = ExtendedSource("veritasellipse",
Exemplo n.º 35
0
import random
import shutil
from pathlib import Path

import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torchvision
from tqdm import tqdm

from . import torch_utils  # , google_utils

matplotlib.rc('font', **{'size': 11})

# Set printoptions
torch.set_printoptions(linewidth=320, precision=5, profile='long')
np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format})  # format short g, %precision=5

# Prevent OpenCV from multithreading (to use PyTorch DataLoader)
cv2.setNumThreads(0)


def floatn(x, n=3):  # format floats to n decimals
    return float(format(x, '.%gf' % n))


def init_seeds(seed=0):
    random.seed(seed)
Exemplo n.º 36
0
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif', size=26)

e = np.load("ephys.npy").item()
a = e['TT1']['spike_amplitudes']

print(a.shape)
#a_embedded = TSNE(n_components=3).fit_transform(a)
a_embedded = TSNE(n_components=2).fit_transform(a)

fig = plt.figure(figsize=(8, 8))
#ax = fig.add_subplot(111, projection='3d')
ax = fig.add_subplot(111)
#ax.scatter(a_embedded[:,0], a_embedded[:,1], a_embedded[:,2])
ax.scatter(a_embedded[:, 0], a_embedded[:, 1])
plt.title('2d clustering tSNE')
# ax.set_xlabel('dimension 1')
# ax.set_ylabel('dimension 2')
# ax.set_zlabel('dimension 3')
# plt.savefig("tSNE_3d.png")
# plt.savefig("tSNE_3d.pdf")
plt.savefig("tSNE_2d.png")
plt.savefig("tSNE_2d.pdf")
Exemplo n.º 37
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 24 21:54:13 2017

@author: yujia
"""


import ipot
import numpy as np
import ot
import matplotlib.pyplot as plt
import matplotlib 
matplotlib.rc('xtick', labelsize=20) 
matplotlib.rc('ytick', labelsize=20) 

   
n = 100

###########data#############
# bin positions
x = np.arange(n, dtype=np.float64)

# Gaussian distributions for input
a1 = 0.5*ot.datasets.get_1D_gauss(n, m=70, s=9)+0.5*ot.datasets.get_1D_gauss(n, m=35, s=9)  # m= mean, s= std
a2 = 0.4*ot.datasets.get_1D_gauss(n, m=60, s=8)+0.6*ot.datasets.get_1D_gauss(n, m=40, s=6)

print('This is the two input margins.' )
plt.plot(x, a1,'o-',color = 'orange',markersize=3)
Exemplo n.º 38
0
def set_matplotlib_rc_params():
    """
    Set matplotlib rcparams for plotting
    """
    font = {'family'        : 'sans-serif',
            'sans-serif'    : 'Helvetica',
            'style'         : 'normal',
            'variant'       : 'normal',
            'weight'        : 'medium',
            'stretch'       : 'normal',
            'size'          : 12.0}
    rc('font', **font)

    legend = {'fontsize'    : 10.0}
    rc('legend', **legend)

    axes = {'titlesize'     : 14.0,
            'labelsize'     : 12.0}
    rc('axes', **axes)
    rc('pdf', fonttype=42)

    ticks = {'direction'    : 'out',
             'labelsize'    : 12.0,
             'major.pad'    : 4,
             'major.size'   : 5,
             'major.width'  : 1.0,
             'minor.pad'    : 4,
             'minor.size'   : 2.5,
             'minor.width'  : 0.75}
    rc('xtick', **ticks)
    rc('ytick', **ticks)
Exemplo n.º 39
0
Arquivo: run.py Projeto: gsi-upm/soba
print(workers_data)
print(model_data)
print(time_data)

# matplotlib.rc('xtick', labelsize=8)
# plt.plot(time_data.Time, sensor_data.Temperature)
# ax = plt.gca()
# #["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
# ax.set_xticklabels(["Day {}\n{:%H:%M}".format(b_, a_) for a_, b_ in zip(time_data.Time, time_data.Day)])
# ax.set_yticklabels(["{:.0f} ºC".format(a) for a in sensor_data.Temperature])
# #ax.set_xticklabels(["(Day %d%s)" % t for t in zip(time_data.Time, time_data.Day)])
# plt.show()

time_data["period"] = time_data.Day.map(str) + time_data.Time.map(str)

matplotlib.rc('xtick', labelsize=8)

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
temp_line = ax1.plot(range(0, len(time_data.Day.index)),
                     sensor_data.Temperature, 'g-')
stress_line = ax2.plot(range(0, len(time_data.Day.index)),
                       model_data,
                       'b-',
                       label='Stress')

#ax1.set_xlabel('Days')
#ax1.set_ylabel('Temperature', color='g')
#ax2.set_ylabel('Stress', color='b')
plt.xticks(range(0, len(time_data.Day.index)), [
Exemplo n.º 40
0
# sys.setdefaultencoding('utf_8_sig')
import matplotlib.pyplot as plt
plt.rcdefaults()

import matplotlib.pyplot as plt1
plt1.rcdefaults()

from datetime import datetime
import random

from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

from matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['AR PL KaitiM GB']})

import json


# 生成cvs文件, 过滤数据, 清洗数据
# del_cvs_row('20171023.csv', 'rank_click_month_after.csv')
# hotRowNum = 0
def pure_cvs_row(fname, newfname, delimiter=',', key='month'):
    with open(fname) as csvin, open(newfname, 'w') as csvout:
        reader = csv.reader(csvin, delimiter=delimiter)
        # print reader
        # rows = [row for row in reader]
        rows = []
        writer = csv.writer(csvout, delimiter=delimiter)
        for row in reader:
Exemplo n.º 41
0
import calculation as cl
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc

font_name = font_manager.FontProperties(
    fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)


# Input user's data and record to original data set(Need only what is handled in this project)
def ui(user, avg, data, direction):

    if direction == 'y':

        print(
            "You can skip some Information. It will be replaced with average.\n"
        )
        for i in [2, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 25]:
            if i == 2:
                name = '(1. male 2. female)'
            elif i == 5:
                name = 'Height'
            elif i == 6:
                name = 'Weight'
            elif i == 7:
                name = 'Waist measurement'
            elif i == 12:
                name = 'Contraction Blood Pressure'
            elif i == 13:
                name = 'Relaxtion Blood Pressure'
Exemplo n.º 42
0
# Version 0.3 May 2017, Gregor Moenke ([email protected])
##################################################################################

from __future__ import division, print_function
import os, sys
from pylab import *
from math import atan2
from os import path, walk
from scipy.optimize import leastsq
from scipy.signal import hilbert, cwt, ricker, lombscargle, welch, morlet
import pandas as pd
from xlrd import *

from matplotlib import rc

rc('font', family='sans-serif', size=18)
rc('lines', markeredgewidth=0)

# global variables
#-----------------------------------------------------------
# thecmap = 'plasma' # the colormap for the wavelet spectra
thecmap = 'viridis'  # the colormap for the wavelet spectra
omega0 = 2 * pi  # central frequency of the mother wavelet
ridge_def_dic = {
    'y0': 0.5,
    'T_ini': 0.1,
    'Nsteps': 15000,
    'max_jump': 3,
    'curve_pen': 0.2,
    'sub_s': 2,
    'sub_t': 2
import torch.nn as nn
import torch.nn.functional as F
import os
import torch
import utils
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib
import numpy as np
from copy import deepcopy

matplotlib.rc('font', family='DejaVu Sans', size=20)

import models.sketchanetfbin as sketchanetfbin
import models.sketchanetwbin as sketchanetwbin

alphas_list = []
betas_list = []
k_list = []
k_list_xnor = []
half_val = -1
old_alphas_list = []

cnt = 0
for i in range(0, 410):

    resume = "savedmodels/sketchanetwbin_tuberlin_epoch_" + str(i) + ".pth.tar"
    if os.path.isfile(resume):
        print("=> loading checkpoint '{}'".format(resume))
        checkpoint = torch.load(resume)
        best_prec1 = checkpoint['best_prec1']
#! /usr/bin/env python3

import matplotlib
matplotlib.use('agg')
matplotlib.rc('text', usetex=True)

import argparse
import matplotlib.pyplot as plt
import numpy as np
import os
import scipy.stats

import misc.bio as bio
import misc.bio_utils.bed_utils as bed_utils
import misc.latex as latex
import misc.math_utils as math_utils

import riboutils.ribo_utils as ribo_utils

default_uniprot = ""
default_uniprot_label = "UniRef"
default_title = ""

def get_orf_lengths(orfs, orf_types):
    m_orf_type = orfs['orf_type'].isin(orf_types)
    lengths = np.array(orfs.loc[m_orf_type, 'orf_len'])
    return lengths

def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="This script creates a line graph showing the length distributions "
Exemplo n.º 45
0
from __future__ import print_function
import matplotlib as mpl

font = {'size': 14}
mpl.rc('font', **font)
mpl.rcParams['toolbar'] = 'None'
mpl.use('TkAgg') # <= the backend is crucial
# figure.canvas.to_string_rgb() should return 24 bits image
# the default Qt5Agg doesn't work

from shutil import which
import argparse
import glob
import os
import time
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from netCDF4 import Dataset
from iosubdomains import Variable
import movietools

def init_figure(fig, str_time, field2d, Lx, Ly):
    """create the figure

    this is where you adapt the figure to your needs
    the function should return the graphical objects to update
    """

    field_size = np.shape(field2d)
    zoom_x = (0.8*fig_size[0])//field_size[1]
@author: me
"""
import os.path
from gdsCAD import *
import numpy as np
import matplotlib.pyplot as plt
from math import log10, floor
import matplotlib
from matplotlib import style
from matplotlib import cm
style.use('ggplot')
from matplotlib import rc
import fitsig2 as fs2
import matplotlib.ticker
rc('text', usetex=True)
rc('figure', figsize=(22,14.2))
matplotlib.rcParams['font.serif'] = 'CMU Serif'
matplotlib.rcParams['font.family'] = 'serif'

matplotlib.rcParams['font.size'] = 22
LARGE_FONT= ("Segoe UI Semilight", 12)
BUTTON_FONT = ("Segoe UI", 10)

plt.ioff()
f,ax = plt.subplots(2,2)

fdict={}

img='Schematic'
r='Resistance $K/W$'
Exemplo n.º 47
0
from premade import MOPRISM
from ea import MOEAD
from _utils import nsga_crossover, gaussian_mutator, random_crossover
from surrogates import RBFN
from sklearn.preprocessing import StandardScaler
from benchmarks import (LZ1, LZ2, LZ3, LZ4, LZ5, LZ7, LZ8, LZ9)

# RBFN surrogate kernels
from pySOT.kernels import CubicKernel
from pySOT.tails import LinearTail

import matplotlib.pyplot as plt
from matplotlib import rc

# Matplotlib
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
# for Palatino and other serif fonts use:
# rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)


def run_sim(n, path, simtitle, REVOLUTION, PROBLEM, seed):

    POP_SIZE = 100
    MAX_GENERATION = 50
    MAX_EPISODE = 100
    MAX_EVAL = 1000
    STOPPING_RULE = 'max_eval'
    MUTATION_RATE = 0.1
    MUTATION_U = 0.
    MUTATION_ST = 0.2
Exemplo n.º 48
0
import numpy as np
import matplotlib.pyplot as pp

from matplotlib import rc
#==============================================================================
rc('text', usetex=True)

markersize = 8
fontsize = 12


def one_by_one(inch_x=3.5, inch_y=3.5):
    fig = pp.figure(figsize=(inch_x, inch_y))
    ax = fig.add_axes([0.15, 0.13, 0.8, 0.81])

    pp.setp(ax.spines.values(), linewidth=0.7)

    ax.tick_params(axis='both', which='major', width=0.7)

    return ax


def one_by_two(inch_x=6.5, inch_y=3.5):
    fig = pp.figure(figsize=(inch_x, inch_y))

    ax_a = fig.add_axes([0.11, 0.14, 0.37, 0.8])

    ax_b = fig.add_axes([0.61, 0.14, 0.37, 0.8])

    ax_a.text(-0.26,
              0.95,
Exemplo n.º 49
0
#Question 7 : Les probabilités de rejet par la méthode de Monte-Carlo
import numpy as np
import matplotlib.pyplot as plt
from random import *
import scipy.special as ss
import sympy as sy
from matplotlib import rc
rc('font', **{'family': 'serif', 'serif': ['Palatino']})
rc('text', usetex=True)
nbs = 10000  #nombre de simulations
a = 2.5  #alpha dans l'énoncé
lbCF = (a - 1 / (6 * a)) / (a - 1)  #lambda_CF dans l'énoncé
lb_s = np.power(((a + 1) / (a - 1)),
                (a + 1) / 2)  #lambda soulignée dans l'énoncé
C = np.exp(a - 1) * ss.gamma(a) / (2 * np.power((a - 1), a))
pRejetCF = 1 - C / lbCF  #la valeur théorique de la probabilité de rejet pour lamba_CF
pRejet_s = 1 - C / lb_s  #la valeur héorique de la probabilité de rejet pour lambda soulignée


def estDansA(X, lb):  #teste si X appartient à A
    if ((2 / (a - 1)) * np.log(X[0]) - np.log(lb * X[1] / X[0]) +
            lb * X[1] / X[0] - 1 <= 0):
        return 1
    return 0


N = 0
M = 0
X = [random(), random()]
for i in range(nbs):
    if estDansA(X, lb_s) == 0:
import tensorflow as tf
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.font_manager
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np

# matplot 에서 한글을 표시하기 위한 설정
rc('font', family='AppleGothic')

plt.rcParams['axes.unicode_minus'] = False

# 단어 벡터를 분석해볼 임의의 문장들
sentences = ["나 고양이 좋다",
             "나 강아지 좋다",
             "나 동물 좋다",
             "강아지 고양이 동물",
             "여자친구 고양이 강아지 좋다",
             "고양이 생선 우유 좋다",
             "강아지 생선 싫다 우유 좋다",
             "강아지 고양이 눈 좋다",
             "나 여자친구 좋다",
             "여자친구 나 싫다",
             "여자친구 나 영화 책 음악 좋다",
             "나 게임 만화 애니 좋다",
             "고양이 강아지 싫다",
             "강아지 고양이 좋다"]

# 문장을 전부 합친 후 공백으로 단어들을 나누고 고유한 단어들로 리스트를 만듭니다.
word_sequence = " ".join(sentences).split()
Exemplo n.º 51
0
    baseEventTimes.size)  # Times between consecutive events.
interArrivalTimes[1:] = baseEventTimes[
    1:] - baseEventTimes[:
                         -1]  # First event is when we start counting time, no interarrival time for it.
""" PLOT THE EMPIRICAL DATA AND FITTED CONDITIONAL INTENSITIES. """
fig = matplotlib.pyplot.figure()
ax = fig.gca()

labelsFontSize = 16
ticksFontSize = 14

fig.suptitle(r"$Conditional\ intensity\ VS\ time$", fontsize=20)
ax.grid(True)
ax.set_xlabel(r'$Time\ (seconds\ since\ epoch)$', fontsize=labelsFontSize)
ax.set_ylabel(r'$\lambda$', fontsize=labelsFontSize)
matplotlib.rc('xtick', labelsize=ticksFontSize)
matplotlib.rc('ytick', labelsize=ticksFontSize)

# Plot the empirical binned data.
ax.plot(empirical_1min.index.to_pydatetime(),
        empirical_1min.values,
        color='blue',
        linestyle='solid',
        marker=None,
        markerfacecolor='blue',
        markersize=12)
empiricalPlot = matplotlib.lines.Line2D([], [],
                                        color='blue',
                                        linestyle='solid',
                                        marker=None,
                                        markerfacecolor='blue',
import os
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

VISUAL_DATA = '../visual'

mpl.rcParams['font.size'] = 15
mpl.rc('lines', linewidth=3)


def _smooth_metric(metr):
    for idx in range(len(metr)):
        if metr[idx] < 0.0:
            if len(metr) > 1:
                if idx == 0:
                    metr[idx] = metr[idx + 1]
                    continue
                if idx == len(metr) - 1:
                    metr[idx] = metr[idx - 1]
                    continue
                metr[idx] = (metr[idx - 1] + metr[idx + 1]) / 2.0
            else:
                metr[idx] = 0.0
    return metr


def _visualize_metric(net_name, metric_name, epochs, train_metric, val_metric):
    plt.clf()
    plt.figure(figsize=(18, 12))
Exemplo n.º 53
0
def annotate3d(centroids, image, **kwargs):
    """Annotates a 3D image and returns a scrollable stack for display in
    IPython.
    
    Parameters
    ----------
    centroids : DataFrame including columns x and y
    image : image array (or string path to image file)
    circle_size : Deprecated.
        This will be removed in a future version of trackpy.
        Use `plot_style={'markersize': ...}` instead.
    color : single matplotlib color or a list of multiple colors
        default None
    invert : If you give a filepath as the image, specify whether to invert
        black and white. Default True.
    ax : matplotlib axes object, defaults to current axes
    split_category : string, parameter to use to split the data into sections
        default None
    split_thresh : single value or list of ints or floats to split
        particles into sections for plotting in multiple colors.
        List items should be ordered by increasing value.
        default None
    imshow_style : dictionary of keyword arguments passed through to
        the `Axes.imshow(...)` command the displays the image
    plot_style : dictionary of keyword arguments passed through to
        the `Axes.plot(...)` command that marks the features

    Returns
    -------
    pims.Frame object containing a three-dimensional RGBA image

    See Also
    --------
    annotate : annotation of 2D images
    """
    if plots_to_frame is None:
        raise ImportError('annotate3d requires pims 0.3 or later. Please '
                          'install/update pims')

    import matplotlib as mpl
    import matplotlib.pyplot as plt

    if image.ndim != 3 and not (image.ndim == 4 and image.shape[-1] in (3, 4)):
        raise ValueError("image has incorrect dimensions. Please input a 3D "
                         "grayscale or RGB(A) image. For 2D image annotation, "
                         "use annotate. Multichannel images can be "
                         "converted to RGB using pims.display.to_rgb.")

    # We want to normalize on the full image and stop imshow from normalizing.
    normalized = (normalize(image) * 255).astype(np.uint8)
    imshow_style = dict(vmin=0, vmax=255)
    if '_imshow_style' in kwargs:
        kwargs['imshow_style'].update(imshow_style)
    else:
        kwargs['imshow_style'] = imshow_style

    max_open_warning = mpl.rcParams['figure.max_open_warning']
    was_interactive = plt.isinteractive()
    try:
        # Suppress warning when many figures are opened
        mpl.rc('figure', max_open_warning=0)
        # Turn off interactive mode (else the closed plots leave emtpy space)
        plt.ioff()

        figures = [None] * len(normalized)
        for i, imageZ in enumerate(normalized):
            fig = plt.figure()
            kwargs['ax'] = fig.gca()
            centroidsZ = centroids[(centroids['z'] > i - 0.5)
                                   & (centroids['z'] < i + 0.5)]
            annotate(centroidsZ, imageZ, **kwargs)
            figures[i] = fig

        result = plots_to_frame(figures,
                                width=512,
                                close_fig=True,
                                bbox_inches='tight')
    finally:
        # put matplotlib back in original state
        if was_interactive:
            plt.ion()
        mpl.rc('figure', max_open_warning=max_open_warning)

    return result
Exemplo n.º 54
0
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from itertools import chain
from functools import partial
from collections import Iterable, Counter, OrderedDict
from isoweek import Week
from pandas_summary import DataFrameSummary
from IPython.lib.display import FileLink
from PIL import Image, ImageEnhance, ImageOps
from sklearn import metrics, ensemble, preprocessing
from operator import itemgetter, attrgetter
from pathlib import Path
from distutils.version import LooseVersion

from matplotlib import pyplot as plt, rcParams, animation
from ipywidgets import interact, interactive, fixed, widgets
matplotlib.rc('animation', html='html5')
np.set_printoptions(precision=5, linewidth=110, suppress=True)

from ipykernel.kernelapp import IPKernelApp
def in_notebook(): return IPKernelApp.initialized()

def in_ipynb():
    try:
        #cls = get_ipython().__class__.__name__
        #return cls == 'ZMQInteractiveShell'
        return False
    except NameError:
        return False

import tqdm as tq
from tqdm import tqdm_notebook, tnrange
Exemplo n.º 55
0
from Hamiltonian_Classes import Hamiltonian, H_table, clock_Hamiltonian, spin_Hamiltonian
from System_Classes import unlocking_System
from Symmetry_Classes import translational, parity, model_sym_data, charge_conjugation
# from Plotting_Classes import eig_overlap,fidelity,entropy,energy_basis
from Non_observables import zm
from Construction_functions import bin_to_int_base_m, int_to_bin_base_m, cycle_bits_state
from Search_functions import find_index_bisection
from State_Classes import zm_state, sym_state, prod_state, bin_state, ref_state
from rw_functions import save_obj, load_obj
from Calculations import level_stats, fidelity, eig_overlap, entropy, site_precession, site_projection, time_evolve_state

from matplotlib import rc
rc('font', **{
    'family': 'sans-serif',
    'sans-serif': ['Computer Modern'],
    'size': 26
})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
# matplotlib.rcParams['figure.dpi'] = 400


def krylov(v, H, krylov_size):
    #generate subspace by repeated application of H
    temp = v
    for n in range(0, krylov_size):
        temp = np.dot(H, temp)
        v = np.vstack((v, temp))
Exemplo n.º 56
0
def analyzePollutionCompare():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    font_name = font_manager.FontProperties(
        fname="c:/Windows/Fonts/malgun.ttf").get_name()
    rc('font', family=font_name)

    # 2016년 대기오염 평균 csv 파일 읽어오기
    # 연도, 이산화질소농도(ppm), 오존농도(ppm), 일산화탄소농도(ppm), 아황산가스(ppm), 미세먼지(㎍/㎥), 초미세먼지(㎍/㎥)
    pollutionData = [[0 for col in range(0)] for row in range(6)]
    polltutionDatafile = 'csv/SeoulAirpollution.csv'
    with open(polltutionDatafile, 'rt') as f:
        rowData = csv.reader(f, delimiter=',')
        for colIdx2, data in enumerate(rowData):
            for colIdx1, d in enumerate(data):
                if colIdx1 == 0: continue

                pollutionData[colIdx1 - 1].insert(colIdx2, float(d))

    # 정규화 처리
    # 공식 : (X - min(X') / (max(X') - min(X'))
    for idx, pol in enumerate(pollutionData):
        minVal = min(pollutionData[idx])
        maxVal = max(pollutionData[idx])
        for valIdx, val in enumerate(pol):
            rangeVal = (maxVal - minVal)
            pollutionData[idx][valIdx] = (pollutionData[idx][valIdx] -
                                          minVal) / rangeVal

    # 오염 제목 리스트
    polName = ["이산화질소", "오존", "일산화탄소", "아황산가스", "미세먼지", "초미세먼지"]

    # X축 월별 배열 정보 선언
    month = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']

    # 비교대상 오염정보 Index
    nPolIndex = 0

    # 2016년 대기오염 정보 plot 설정
    f, axarr = plt.subplots(2, 3)

    # 비교대상 오염정보와 타 오염정보를 비교함
    xIdx = 0
    yIdx = 0
    for idx, data in enumerate(pollutionData):
        if idx == nPolIndex: continue

        axarr[xIdx, yIdx].plot(month,
                               pollutionData[nPolIndex],
                               'b-o',
                               label=polName[nPolIndex])
        axarr[xIdx, yIdx].plot(month, data, 'r-s', label=polName[idx])
        axarr[xIdx, yIdx].set_title(polName[nPolIndex] + " / " + polName[idx])
        #axarr[xIdx, yIdx].set_xlabel("월")
        axarr[xIdx, yIdx].set_ylabel("오염도 ")
        axarr[xIdx, yIdx].legend()

        yIdx += 1

        if (yIdx > 2):
            xIdx += 1
            yIdx = 0

    # 그래프 노출
    plt.show()
# http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from matplotlib import rc, rcParams
import matplotlib.dates as dates

# activate latex text rendering
rc('text', usetex=True)
rc('axes', linewidth=2)
rc('font', weight='bold')
rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath']

Dropout_Bald_TanH_0p005 = np.load('Dropout_Bald_TanH_0p005.npy')
Dropout_Bald_V2 = np.load('Dropout_Bald_trial2.npy')
Dropout_Bald_V3 = np.load('Dropout_Bald_trial3.npy')
Dropout_Random_V3 = np.load('Dropout_Random_trial3.npy')

BB_Alpha_Random_0p5 = np.load('BBAlpha_0p5_Random.npy')
BB_Alpha_Random_10m6 = np.load('BBAlpha_10em6_Random.npy')
BB_Alpha_Random_1 = np.load('BBAlpha_1_Random.npy')

PBP_Bald = np.load('PBP_Bald.npy')
PBP_Random = np.load('PBP_Random.npy')

Dropout_Bald_YarinConfigs = np.load('Dropout_Bald_YarinConfigs.npy')
Dropout_Bald_TanH_0p05 = np.load('Dropout_Bald_NewConfigsV4.npy')

AEPDGP_Random = np.load('AEPDGP_Random.npy')

Q = np.arange(20, 401, 1)
Exemplo n.º 58
0
import pandas as pd  # 데이터 저장하고 가공처리
import matplotlib as mpl  # 그래프 그리기
import matplotlib.pyplot as plt  # 그래프 그리기

# csv 파일 읽어 dataFrame 객체 만들고 , 인덱스 컬럼 point 설정
df = pd.read_csv('weather.csv', index_col='point', encoding='euc-kr')
# print(df)
# df.loc(label-location)을 이용해 특정 인덱스의 데이터만 가져오도록 함
city_df = df.loc[['서울', '인천', '대전', '대구', '광주', '부산', '울산']]
print(city_df)

# 데이터의 폰트를 설정한다
# matplotlib에서는 기본적으로 한글 표시가 되지 않으므로 한글 폰트를 지정 설정한다
font_name = mpl.font_manager.FontProperties(
    fname='C:/Windows/Fonts/malgun.ttf').get_name()
mpl.rc('font', family=font_name)

# 차트 종류 제목 크기 범례 폰트 크기 설정
ax = city_df.plot(kind='bar',
                  title='날씨',
                  figsize=(12, 4),
                  legend=True,
                  fontsize=12)
ax.set_xlabel('도시', fontsize=12)
ax.set_ylabel('기온/습도', fontsize=12)
ax.legend(['기온', '습도'], fontsize=12)

plt.show()
Exemplo n.º 59
0
matavg  = df['mat'].mean()
print(matavg)   #   78.0

# 학생들 중에 수학점수가 평균이하인 학생들의 정보를 추출
lower_math = df[df['mat'] <= matavg]

print(lower_math)
'''
            class  kor  eng  mat  bio
    name                             
    andrew      1   45   45   56   98
    dan         1   45   65   78   98
    paul        2   87   67   65   56
    walter      2   89   98   78   78
    oscar       2  100   78   56   65
    hugh        2   98   45   56   54
'''

rc('font',family=font_manager.FontProperties(fname="C:/WINDOWS/Fonts/H2GPRM.TTF").get_name())

print(plt.colormaps())  # 무슨색이 있는 지 확인
'''
['Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis', 'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'magma', 'magma_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'ocean_r', 'pink', 'pink_r', 'plasma', 'plasma_r', 'prism', 'prism_r', 'rainbow', 'rainbow_r', 'seismic', 'seismic_r', 'spring', 'spring_r', 'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain', 'terrain_r', 'twilight', 'twilight_r', 'twilight_shifted', 'twilight_shifted_r', 'viridis', 'viridis_r', 'winter', 'winter_r']

'''

# 필요한 칼럼만 추출
lower_math[[ 'kor' , 'eng' , 'mat' , 'bio']].plot(kind='bar', colormap='winter')
plt.title("수학점수가 평균이하인 학생")
plt.show()
Exemplo n.º 60
0
                                       origin_gdf[f'{exp}_td'] * 0.07 * 3 *
                                       365)
        origin_gdf[f'{exp}_bus_em_pc'] = origin_gdf[
            f'{exp}_bus_em'] / origin_gdf[f'population_{exp}']
        origin_gdf[f'{exp}_total_em'] = origin_gdf[
            f'{exp}_car_em'] + origin_gdf[f'{exp}_bus_em']
        origin_gdf[f'{exp}_total_em_pc'] = origin_gdf[
            f'{exp}_total_em'] / origin_gdf[f'population_{exp}']
        origin_gdf = origin_gdf.to_crs(26910)
        return blocks_gdf


pd.set_option('display.width', 700)
fm.fontManager.ttflist += fm.createFontList(
    ['/Volumes/Samsung_T5/Fonts/roboto/Roboto-Light.ttf'])
rc('font', family='Roboto', weight='light')
name = 'Hillside Quadra'
region = 'Capital Regional District, British Columbia'
directory = f'/Volumes/Samsung_T5/Databases/Sandbox/{name}'
experiments = ['e2', 'e3']  # ['e0', 'e1', 'e2', 'e3']
em_modes = ['car', 'bus', 'total']
exp_df = pd.DataFrame()
macc = pd.DataFrame()
tf_years = 20
GeoPackage = f'/Volumes/Samsung_T5/Databases/Capital Regional District, British Columbia.gpkg'

for infra, values in {
        'bus': 'Frequent transit',
        'bike': 'Cycling lanes'
}.items():