當前位置: 首頁>>代碼示例>>Python>>正文


Python matplotlib.use方法代碼示例

本文整理匯總了Python中matplotlib.use方法的典型用法代碼示例。如果您正苦於以下問題:Python matplotlib.use方法的具體用法?Python matplotlib.use怎麽用?Python matplotlib.use使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib的用法示例。


在下文中一共展示了matplotlib.use方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: plot_coordinates

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def plot_coordinates(coordinates, plot_path, markers, label_names, fig_num):
    matplotlib.use('svg')
    import matplotlib.pyplot as plt

    plt.figure(fig_num)
    for i in range(len(markers) - 1):
        plt.scatter(x=coordinates[markers[i]:markers[i + 1], 0],
                    y=coordinates[markers[i]:markers[i + 1], 1],
                    marker=plot_markers[i % len(plot_markers)],
                    c=colors[i % len(colors)],
                    label=label_names[i], alpha=0.75)

    plt.legend(loc='upper right', fontsize='x-large')
    plt.axis('off')
    plt.savefig(fname=plot_path, format="svg", bbox_inches='tight', transparent=True)
    plt.close() 
開發者ID:vineetjohn,項目名稱:linguistic-style-transfer,代碼行數:18,代碼來源:tsne_visualizer.py

示例2: getFreeId

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def getFreeId():
    import pynvml 

    pynvml.nvmlInit()
    def getFreeRatio(id):
        handle = pynvml.nvmlDeviceGetHandleByIndex(id)
        use = pynvml.nvmlDeviceGetUtilizationRates(handle)
        ratio = 0.5*(float(use.gpu+float(use.memory)))
        return ratio

    deviceCount = pynvml.nvmlDeviceGetCount()
    available = []
    for i in range(deviceCount):
        if getFreeRatio(i)<70:
            available.append(i)
    gpus = ''
    for g in available:
        gpus = gpus+str(g)+','
    gpus = gpus[:-1]
    return gpus 
開發者ID:uci-cbcl,項目名稱:DeepLung,代碼行數:22,代碼來源:utils.py

示例3: set_device

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def set_device(use_gpu, multi_gpu, _log):
    # Decide which device to use.
    if use_gpu and not torch.cuda.is_available():
        raise RuntimeError('use_gpu is True but CUDA is not available')

    if use_gpu:
        device = torch.device('cuda')
        torch.set_default_tensor_type('torch.cuda.FloatTensor')
    else:
        device = torch.device('cpu')

    if multi_gpu and torch.cuda.device_count() == 1:
        raise RuntimeError('Multiple GPU training requested, but only one GPU is available.')

    if multi_gpu:
        _log.info('Using all {} GPUs available'.format(torch.cuda.device_count()))

    return device 
開發者ID:bayesiains,項目名稱:nsf,代碼行數:20,代碼來源:images.py

示例4: hzfunc

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def hzfunc(self,label):
        ax = self.hzdict[label]
        num = int(label.replace("plot ",""))
        #print "Selected axis number:", num
        #global mainnum
        self.mainnum = num
        # drawtype is 'box' or 'line' or 'none'
        toggle_selector.RS = RectangleSelector(ax, self.line_select_callback,
                                           drawtype='box', useblit=True,
                                           button=[1,3], # don't use middle button
                                           minspanx=5, minspany=5,
                                           spancoords='pixels',
                                           rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.2, fill=True))

        #plt.connect('key_press_event', toggle_selector)
        plt.draw() 
開發者ID:geomagpy,項目名稱:magpy,代碼行數:18,代碼來源:mpplot.py

示例5: validation

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def validation(self, sess, cells_no, exp_folder, train_step):
        """
        Method that initiates some validation steps of the current model.

        Parameters
        ----------
        sess : Session
            The TF Session in use.
        cells_no : int
            Number of cells to use for the validation step.
        exp_folder : str
            Path to the job folder in which the outputs will be saved.
        train_step : int
            Index of the current training step.

        Returns
        -------
        """
        print("Find tSNE embedding for the generated and the validation cells")
        self.generate_tSNE_image(sess, cells_no, exp_folder, train_step) 
開發者ID:imsb-uke,項目名稱:scGAN,代碼行數:22,代碼來源:scGAN.py

示例6: evaluate_pi

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def evaluate_pi(q, task):
    # use Monte Carlo method to estimate the state value
    runs = 1000
    returns = []
    for r in range(runs):
        rewards = 0
        state = 0
        while state < task.n_states:
            action = argmax(q[state])
            state, r = task.step(state, action)
            rewards += r
        returns.append(rewards)
    return np.mean(returns)

# perform expected update from a uniform state-action distribution of the MDP @task
# evaluate the learned q value every @eval_interval steps 
開發者ID:ShangtongZhang,項目名稱:reinforcement-learning-an-introduction,代碼行數:18,代碼來源:trajectory_sampling.py

示例7: _twopop_IM

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def _twopop_IM(
        engine_id, out_dir, seed,
        NA=1000, N1=500, N2=5000, T=1000, M12=0, M21=0, pulse=None, samples=None,
        **sim_kwargs):
    species = stdpopsim.get_species("AraTha")
    contig = species.get_contig("chr5", length_multiplier=0.01)  # ~270 kb
    contig = irradiate(contig)
    model = stdpopsim.IsolationWithMigration(
            NA=NA, N1=N1, N2=N2, T=T, M12=M12, M21=M21)
    if pulse is not None:
        model.demographic_events.append(pulse)
        model.demographic_events.sort(key=lambda x: x.time)
    # XXX: AraTha has species.generation_time == 1, but there is the potential
    # for this to mask bugs related to generation_time scaling, so we use 3 here.
    model.generation_time = 3
    if samples is None:
        samples = model.get_samples(50, 50, 0)
    engine = stdpopsim.get_engine(engine_id)
    t0 = time.perf_counter()
    ts = engine.simulate(model, contig, samples, seed=seed, **sim_kwargs)
    t1 = time.perf_counter()
    out_file = out_dir / f"{seed}.trees"
    ts.dump(out_file)
    return out_file, t1 - t0 
開發者ID:popsim-consortium,項目名稱:stdpopsim,代碼行數:26,代碼來源:validation.py

示例8: _create_solutions_model

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def _create_solutions_model(self):
        """
        Create pymc model components for true concentrations of source receptor and ligand solutions.

        Populates the following fields:
        * parameter_names['concentrations'] : parameters associated with true concentrations of receptor and ligand solutions
        """
        # Determine solutions in use in plate
        solutions_in_use = set()
        for well in self.wells:
            for shortname in well.properties['contents']:
                solutions_in_use.add(shortname)
        print('Solutions in use: %s' % str(solutions_in_use))

        # Retain only solutions that appear in the plate
        self.solutions = { shortname : self.solutions[shortname] for shortname in solutions_in_use }

        self.parameter_names['solution concentrations'] = list()
        for solution in self.solutions.values():
            if solution.species is None:
                continue # skip buffers or pure solvents
            name = 'log concentration of %s' % solution.shortname
            self.model[name] = LogNormalWrapper(name, mean=solution.concentration.to_base_units().m, stddev=solution.uncertainty.to_base_units().m)
            self.parameter_names['solution concentrations'].append(name) 
開發者ID:choderalab,項目名稱:assaytools,代碼行數:26,代碼來源:analysis.py

示例9: chunkIt

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def chunkIt(seq, num):
    """
    This comes from https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length
    I will use it to create a bunch of lists for sequential clustering

    Args:
        seq: The initial list for chunking
        num: The number of items in each chunk

    Return:
        A chunked list with roughly equal numbers of elements

    Author: Max Shawabkeh


    """
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out 
開發者ID:LSDtopotools,項目名稱:LSDMappingTools,代碼行數:27,代碼來源:LSDMap_HillslopeMorphology.py

示例10: __generic_histo__

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def __generic_histo__(self, vector, labels):
        # This function just calls the appropriate plot function for our available
        # interface.  Same thing as generic_ci, but for a histogram.
        if self.interface == 'text':
            self.__terminal_histo__(vector, labels)
        else:
            try:
                import matplotlib
                matplotlib.use('TkAgg')
                from matplotlib import pyplot as plt
                plt.bar(list(range(0, np.array(vector).shape[0])), vector, linewidth=0, align='center', color='gold', tick_label=labels)
                plt.show()
            except:
                print('Unable to import plotting interface.  An X server ($DISPLAY) is required.')
                self.__terminal_histo__(h5file, vector, labels)
                return 1 
開發者ID:westpa,項目名稱:westpa,代碼行數:18,代碼來源:plot.py

示例11: __init__

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def __init__(self, kaldi_root, hop=160, win=400, sr=16000,
                    num_mel_bins=40, num_ceps=13, der_order=2,
                    name='kaldimfcc'):

        super(KaldiMFCC, self).__init__(kaldi_root=kaldi_root, 
                                        hop=hop, win=win, sr=sr)

        self.num_mel_bins = num_mel_bins
        self.num_ceps = num_ceps
        self.der_order=der_order

        cmd = "ark:| {}/src/featbin/compute-mfcc-feats --print-args=false "\
               "--use-energy=false --snip-edges=false --num-ceps={} "\
               "--frame-length={} --frame-shift={} "\
               "--num-mel-bins={} --sample-frequency={} ark:- ark:- |"\
               " {}/src/featbin/add-deltas --print-args=false "\
               "--delta-order={} ark:- ark:- |"

        self.cmd = cmd.format(self.kaldi_root, self.num_ceps,
                              self.frame_length, self.frame_shift,
                              self.num_mel_bins, self.sr, self.kaldi_root,
                              self.der_order)
        self.name = name 
開發者ID:santi-pdp,項目名稱:pase,代碼行數:25,代碼來源:transforms.py

示例12: plot_images

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def plot_images(ax, images, shape, color = False):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    # flip 0 to 1
    images = 1.0 - images

    images = reshape_and_tile_images(images, shape, n_cols=len(images))
    if color:
        from matplotlib import cm
        plt.imshow(images, cmap=cm.Greys_r, interpolation='nearest')
    else:
        plt.imshow(images, cmap='Greys')
    ax.axis('off') 
開發者ID:YingzhenLi,項目名稱:Dropout_BBalpha,代碼行數:18,代碼來源:loading_utils.py

示例13: get_lat_lon_from_csv

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def get_lat_lon_from_csv(csv_file, lats=[], lons=[]):
    """
    Retrieves the last two rows of a CSV formatted file to use as latitude
    and longitude.
    Returns two lists (latitudes and longitudes).

    Example CSV file:
    119.80.39.54, Beijing, China, 39.9289, 116.3883
    101.44.1.135, Shanghai, China, 31.0456, 121.3997
    219.144.17.74, Xian, China, 34.2583, 108.9286
    64.27.26.7, Los Angeles, United States, 34.053, -118.2642
    """
    with contextlib.closing(csv_file):
        reader = csv.reader(csv_file)
        for row in reader:
            lats.append(row[-2])
            lons.append(row[-1])

    return lats, lons 
開發者ID:pieqq,項目名稱:PyGeoIpMap,代碼行數:21,代碼來源:pygeoipmap.py

示例14: mpl_hist_arg

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def mpl_hist_arg(value=True):
    """Find the appropriate `density` kwarg for our given matplotlib version.

    This will determine if we should use `normed` or `density`. Additionally,
    since this is a kwarg, the user can supply a value (True or False) that
    they would like in the output dictionary.

    Parameters
    ----------
    value : bool, optional (default=True)
        The boolean value of density/normed

    Returns
    -------
    density_kwarg : dict
        A dictionary containing the appropriate density kwarg for the
        installed  matplotlib version, mapped to the provided or default
        value
    """
    import matplotlib

    density_kwarg = 'density' if matplotlib.__version__ >= '2.1.0'\
        else 'normed'
    return {density_kwarg: value} 
開發者ID:alkaline-ml,項目名稱:pmdarima,代碼行數:26,代碼來源:matplotlib.py

示例15: pair_visual

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import use [as 別名]
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:43,代碼來源:utils.py


注:本文中的matplotlib.use方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。