Python matplotlib.pyplot 模块,rcParams() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.rcParams()

项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def ezrc(fontSize=22., lineWidth=2., labelSize=None, tickmajorsize=10,
         tickminorsize=5, figsize=(8, 6)):
    """
    slides - Define params to make pretty fig for slides
    """
    from pylab import rc, rcParams
    if labelSize is None:
        labelSize = fontSize + 5
    rc('figure', figsize=figsize)
    rc('lines', linewidth=lineWidth)
    rcParams['grid.linewidth'] = lineWidth
    rcParams['font.sans-serif'] = ['Helvetica']
    rcParams['font.serif'] = ['Helvetica']
    rcParams['font.family'] = ['Times New Roman']
    rc('font', size=fontSize, family='serif', weight='bold')
    rc('axes', linewidth=lineWidth, labelsize=labelSize)
    rc('legend', borderpad=0.1, markerscale=1., fancybox=False)
    rc('text', usetex=True)
    rc('image', aspect='auto')
    rc('ps', useafm=True, fonttype=3)
    rcParams['xtick.major.size'] = tickmajorsize
    rcParams['xtick.minor.size'] = tickminorsize
    rcParams['ytick.major.size'] = tickmajorsize
    rcParams['ytick.minor.size'] = tickminorsize
    rcParams['text.latex.preamble'] = ["\\usepackage{amsmath}"]
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def update_inspect(self, indices, add_or_remove=None, link=True):
        all_colors = colorConverter.to_rgba_array(plt.rcParams['axes.color_cycle'])

        if add_or_remove is 'add':
            indices = set(self.inspect_points) | set(indices)
        elif add_or_remove is 'remove':
            indices = set(self.inspect_points) - set(indices)

        self.inspect_points = sorted(indices)
        # We use a deterministic mapping to colors, based on their index
        self.inspect_colors = [all_colors[idx % len(all_colors)]
                               for idx in self.inspect_points]

        if link:
            self.inspect_templates = set()
            all_templates = numpy.unique(self.pairs[list(indices)].flatten())
            indices = []
            for i in all_templates:
                indices += [numpy.where(self.to_consider == i)[0][0]]
            self.update_inspect_template(indices, 'add', False)

        self.update_score_plot()
        self.update_detail_plot()
        self.update_data_plot()
        self.update_waveforms()
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def update_inspect(self, indices, add_or_remove=None):

        all_colors = colorConverter.to_rgba_array(plt.rcParams['axes.color_cycle'])

        if add_or_remove is 'add':
            indices = set(self.inspect_points) | set(indices)
        elif add_or_remove is 'remove':
            indices = set(self.inspect_points) - set(indices)

        self.inspect_points = sorted(indices)
        # We use a deterministic mapping to colors, based on their index
        self.inspect_colors = [all_colors[idx % len(all_colors)]
                               for idx in self.inspect_points]

        self.update_electrode_plot()
        self.update_data_plot()
项目:deep-time-reading    作者:felixduvallet    | 项目源码 | 文件源码
def _setup_axes():
    plt.rcParams['toolbar'] = 'None'
    fig = plt.figure(figsize=(fig_size, fig_size), facecolor='w')
    ax = plt.subplot(111, polar=True)
    ax.get_yaxis().set_visible(False)

    # 12 labels, clockwise
    marks = np.linspace(360. / 12, 360, 12, endpoint=True)
    ax.set_thetagrids(marks, map(lambda m: int(m / 30), marks), frac=.85,
                      size='x-large')
    ax.set_theta_direction(-1)
    ax.set_theta_offset(np.pi / 2)
    ax.grid(None)

    # These are the clock hands. We update the coordinates later.
    bars = ax.bar([0.0, 0.0, 0.0], lengths,
                  width=widths, bottom=0.0, color=colors, linewidth=0)

    return fig, ax, bars
项目:CodeReviewClub    作者:iastro-pt    | 项目源码 | 文件源码
def __call__(self, x, pos=None):
    # call the original ScalarFormatter
    rv = ticker.ScalarFormatter.__call__(self, x, pos)
    # check if we really use TeX
    if plt.rcParams["text.usetex"]:
      # if we have the string ^{- there is a negative exponent
      # where the minus sign is replaced by the short hyphen
      rv = re.sub(r'-', r'\mhyphen', rv)

    if rv.endswith('.0'):
      rv = rv.replace('.0', '')

    return rv



### for the A&A article class
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def niceFigure(useLatex=True):
    from matplotlib import rcParams
    import matplotlib.pyplot as plt
    # rcParams.update({'figure.autolayout': True})
    if useLatex is True:
        plt.rc('text', usetex=True)
        plt.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    rcParams['xtick.direction'] = 'out'
    rcParams['ytick.direction'] = 'out'
    rcParams['xtick.major.width'] = 1
    rcParams['ytick.major.width'] = 1
    #
    # cbar.outline.set_edgecolor('black')
    # cbar.outline.set_linewidth(1)
    #
    return 0
项目:RealtimeFacialEmotionRecognition    作者:sushant3095    | 项目源码 | 文件源码
def make_net(mean=None, net_dir='VGG_S_rgb'):
    # net_dir specifies type of network 
    # Options are: (rgb, lbp, cyclic_lbp, cyclic_lbp_5, cyclic_lbp_10)

    caffe_root = '/home/gshine/Data/Caffe'
    sys.path.insert(0, caffe_root + 'python')

    plt.rcParams['figure.figsize'] = (10, 10)
    plt.rcParams['image.interpolation'] = 'nearest'
    plt.rcParams['image.cmap'] = 'gray'

    net_root = 'models'

    net_pretrained = os.path.join(net_root, net_dir, 'EmotiW_VGG_S.caffemodel')
    net_model_file = os.path.join(net_root, net_dir, 'deploy.prototxt')
    VGG_S_Net = caffe.Classifier(net_model_file, net_pretrained,
                       mean=mean,
                       channel_swap=(2,1,0),
                       raw_scale=255,
                       image_dims=(256, 256))
    return VGG_S_Net

# Load a minibatch of images
项目:inception-face-shape-classifier    作者:adonistio    | 项目源码 | 文件源码
def plot_images(image, Caption1):

    plt.close()

    plt.rcParams['text.usetex'] = False
    plt.rcParams['font.size'] = 10
    plt.rcParams['font.family'] = 'Arial'

    fig, ax = plt.subplots(1, 1)
    ax.imshow(image)
    xlabel = Caption1
    ax.set_xlabel(xlabel)
    ax.set_xticks([])
    ax.set_yticks([])
    plt.show()

    #plt.close()
项目:ptreeopt    作者:jdherman    | 项目源码 | 文件源码
def init_plotting(w,h):
  sns.set_style('whitegrid')
  plt.rcParams['figure.figsize'] = (w,h)
  plt.rcParams['font.size'] = 13
  plt.rcParams['font.family'] = 'OfficinaSanITCBoo'
  # plt.rcParams['font.weight'] = 'bold'
  plt.rcParams['axes.labelsize'] = 1.1*plt.rcParams['font.size']
  plt.rcParams['axes.titlesize'] = 1.1*plt.rcParams['font.size']
  plt.rcParams['legend.fontsize'] = plt.rcParams['font.size']
  plt.rcParams['xtick.labelsize'] = plt.rcParams['font.size']
  plt.rcParams['ytick.labelsize'] = plt.rcParams['font.size']





# snapshots = pickle.load(open('results/hist-fit-fp/snapshots-fit-hist.pkl', 'rb'))
项目:ptreeopt    作者:jdherman    | 项目源码 | 文件源码
def init_plotting(w,h):
  sns.set_style('whitegrid')
  plt.rcParams['figure.figsize'] = (w,h)
  plt.rcParams['font.size'] = 13
  plt.rcParams['font.family'] = 'OfficinaSanITCBoo'
  # plt.rcParams['font.weight'] = 'bold'
  plt.rcParams['axes.labelsize'] = 1.1*plt.rcParams['font.size']
  plt.rcParams['axes.titlesize'] = 1.1*plt.rcParams['font.size']
  plt.rcParams['legend.fontsize'] = plt.rcParams['font.size']
  plt.rcParams['xtick.labelsize'] = plt.rcParams['font.size']
  plt.rcParams['ytick.labelsize'] = plt.rcParams['font.size']





# snapshots = pickle.load(open('results/hist-fit-fp/snapshots-fit-hist.pkl', 'rb'))
# snapshots = pickle.load(open('results/hist-tocs/snapshots-tocs-depth-3-seed-0.pkl', 'rb'))
项目:yolo-tf    作者:ruiminshen    | 项目源码 | 文件源码
def __init__(self, sess, names, cell_width, cell_height, image, labels, model, feed_dict):
        self.sess = sess
        self.names = names
        self.cell_width, self.cell_height = cell_width, cell_height
        self.image, self.labels = image, labels
        self.model = model
        self.feed_dict = feed_dict
        self.fig = plt.figure()
        self.ax = self.fig.gca()
        height, width, _ = image.shape
        self.scale = [width / self.cell_width, height / self.cell_height]
        self.ax.imshow(image)
        self.plots = utils.visualize.draw_labels(self.ax, names, width, height, cell_width, cell_height, *labels)
        self.ax.set_xticks(np.arange(0, width, width / cell_width))
        self.ax.set_yticks(np.arange(0, height, height / cell_height))
        self.ax.grid(which='both')
        self.ax.tick_params(labelbottom='off', labelleft='off')
        self.fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.colors = [prop['color'] for _, prop in zip(names, itertools.cycle(plt.rcParams['axes.prop_cycle']))]
项目:openai_lab    作者:kengz    | 项目源码 | 文件源码
def scoped_mpl_import():
    import matplotlib
    matplotlib.rcParams['backend'] = MPL_BACKEND

    import matplotlib.pyplot as plt
    plt.rcParams['toolbar'] = 'None'  # mute matplotlib toolbar

    import seaborn as sns
    sns.set(style="whitegrid", color_codes=True, font_scale=1.0,
            rc={'lines.linewidth': 1.0,
                'backend': matplotlib.rcParams['backend']})
    palette = sns.color_palette("Blues_d")
    palette.reverse()
    sns.set_palette(palette)

    return (matplotlib, plt, sns)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def mpl_style_cb(key):
    warnings.warn(pc_mpl_style_deprecation_warning, FutureWarning,
                  stacklevel=5)

    import sys
    from pandas.tools.plotting import mpl_stylesheet
    global style_backup

    val = cf.get_option(key)

    if 'matplotlib' not in sys.modules.keys():
        if not val:  # starting up, we get reset to None
            return val
        raise Exception("matplotlib has not been imported. aborting")

    import matplotlib.pyplot as plt

    if val == 'default':
        style_backup = dict([(k, plt.rcParams[k]) for k in mpl_stylesheet])
        plt.rcParams.update(mpl_stylesheet)
    elif not val:
        if style_backup:
            plt.rcParams.update(style_backup)

    return val
项目:segmentation    作者:zengyu714    | 项目源码 | 文件源码
def show_slices(im_3d, indices=None):
    """ Function to display slices of 3-d image """

    plt.rcParams['image.cmap'] = 'gray'

    if indices is None:
        indices = np.array(im_3d.shape) // 2
    assert len(indices) == 3, """Except 3-d array, but receive %d-d array
    indexing.""" % len(indices)

    x_th, y_th, z_th = indices
    fig, axes = plt.subplots(1, 3)
    axes[0].imshow(im_3d[x_th, :, :])
    axes[1].imshow(im_3d[:, y_th, :])
    axes[2].imshow(im_3d[:, :, z_th])
    plt.suptitle("Center slices for spine image")
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def get_rcParams(self):
        """Get an rcParams dict for this theme.

        Notes
        -----
        Subclasses should not need to override this method method as long as
        self._rcParams is constructed properly.

        rcParams are used during plotting. Sometimes the same theme can be
        achieved by setting rcParams before plotting or a post_plot_callback
        after plotting. The choice of how to implement it is is a matter of
        convenience in that case.

        There are certain things can only be themed after plotting. There
        may not be an rcParam to control the theme or the act of plotting
        may cause an entity to come into existence before it can be themed.

        """
        rcParams = deepcopy(self._rcParams)
        return rcParams
项目:emotion-conv-net    作者:GautamShine    | 项目源码 | 文件源码
def make_net(mean=None, net_dir='VGG_S_rgb'):
    # net_dir specifies type of network 
    # Options are: (rgb, lbp, cyclic_lbp, cyclic_lbp_5, cyclic_lbp_10)

    caffe_root = '/home/gshine/Data/Caffe'
    sys.path.insert(0, caffe_root + 'python')

    plt.rcParams['figure.figsize'] = (10, 10)
    plt.rcParams['image.interpolation'] = 'nearest'
    plt.rcParams['image.cmap'] = 'gray'

    net_root = 'models'

    net_pretrained = os.path.join(net_root, net_dir, 'EmotiW_VGG_S.caffemodel')
    net_model_file = os.path.join(net_root, net_dir, 'deploy.prototxt')
    VGG_S_Net = caffe.Classifier(net_model_file, net_pretrained,
                       mean=mean,
                       channel_swap=(2,1,0),
                       raw_scale=255,
                       image_dims=(256, 256))
    return VGG_S_Net

# Load a minibatch of images
项目:matplotlib    作者:DaveL17    | 项目源码 | 文件源码
def getDeviceStateList(self, dev):
        """ getDeviceStateList is called automatically by
        dev.stateListOrDisplayStateIdChanged().
        """
        state_list = indigo.PluginBase.getDeviceStateList(self, dev)

        if dev.deviceTypeId == 'rcParamsDevice':

            for key in rcParams.iterkeys():
                key = key.replace('.', '_')
                dynamic_state = self.getDeviceStateDictForStringType(key, key, key)
                state_list.append(dynamic_state)
                state_list.append(self.getDeviceStateDictForStringType('onOffState', 'onOffState', 'onOffState'))

            return state_list

        else:
            return state_list
项目:jd_analysis    作者:awolfly9    | 项目源码 | 文件源码
def analysis_mobile(self):
        # self.record_result('<strong style="color: black; font-size: 24px;">???????????????...</strong>')

        fig_size = plt.rcParams["figure.figsize"]
        plt.figure(figsize = (2.4, 2.4))

        obj = self.data_frame['is_mobile']
        obj = obj.value_counts()

        obj = obj.rename({1: '???', 0: 'PC'})
        plt.pie(x = obj.values, autopct = '%.0f%%', radius = 0.7, labels = obj.index, startangle = 180)

        plt.title('?????/ PC ????')

        plt.tight_layout()
        filename = '%s_mobile.png' % self.product_id
        plt.savefig('%s/%s' % (utils.get_save_image_path(), filename))
        plt.figure(figsize = fig_size)
        plt.clf()
        result = utils.get_image_src(filename = filename)
        self.record_result(result, type = 'image')

    # ????????????
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def update_inspect_template(self, indices, add_or_remove=None, link=True):
        all_colors = colorConverter.to_rgba_array(plt.rcParams['axes.color_cycle'])
        indices = self.to_consider[list(indices)]

        for i in xrange(len(indices)):
            indices[i] -= [numpy.sum(self.to_delete <= indices[i])]

        if add_or_remove is 'add':
            indices = set(self.inspect_templates) | set(indices)
        elif add_or_remove is 'remove':
            indices = set(self.inspect_templates) - set(indices)

        self.inspect_templates = sorted(indices)

        # We use a deterministic mapping to colors, based on their index
        self.inspect_colors_templates = [all_colors[idx % len(all_colors)]
                               for idx in self.inspect_templates]

        is_selected_1 = numpy.where(numpy.in1d(self.pairs[:, 0], self.inspect_templates) == True)[0]
        is_selected_2 = numpy.where(numpy.in1d(self.pairs[:, 1], self.inspect_templates) == True)[0]
        is_selected = numpy.unique(numpy.concatenate((is_selected_1, is_selected_2)))
        if link:
            self.inspect_points = set()
            self.update_inspect(is_selected, 'add', False)

        self.update_score_plot()
        self.update_detail_plot()
        self.update_data_plot()
        self.update_waveforms()
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def _enter_plotting(self, fontsize=7):
        """assumes that a figure is open """
        from matplotlib import pyplot
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        # if font size deviates from default, we assume this is on purpose and hence leave it alone
        if pyplot.rcParams['font.size'] == pyplot.rcParamsDefault['font.size']:
            pyplot.rcParams['font.size'] = fontsize
        # was: pyplot.hold(False)
        # pyplot.gcf().clear()  # opens a figure window, if non exists
        pyplot.ioff()
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def _finalize_plotting(self):
        from matplotlib import pyplot
        pyplot.tight_layout(rect=(0, 0, 0.96, 1))
        pyplot.draw()  # update "screen"
        pyplot.ion()  # prevents that the execution stops after plotting
        pyplot.show()
        pyplot.rcParams['font.size'] = self.original_fontsize
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def latexify(params=PARAMS, new_backend='pgf'):
    '''
    Set up Matplotlib's RC params for LaTeX plotting.

    Call this function before plotting the first figure.

    Parameters
    ----------
    params : Optional[dict]
        A dictionary containing the RC params that need to be updated. Default
        is ``PARAMS``. The defaults should be okay for most cases, but
        ``PARAMS`` can be updated via ``.update()`` as well.

    new_backend : Optional[str|None]
        The backend to switch too. Default is PGF, which allows a nicer PDF
        output too.

    Raises
    ------
    ValueError
        If the new backend is not supported.

    Example
    -------
    >>> params = PARAMS.copy()
    >>> params.update({'font.family': 'sans-serif'})
    >>> latexify(params)

    '''
    plt.rcParams.update(params)
    if new_backend is not None:
        try:
            plt.switch_backend(new_backend)
        except ValueError:
            logger.error(f'Backend not supported: {new_backend!r}')
            raise
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def revert():
    '''
    Return to the settings before running ``latexify()`` and updating params.

    '''
    plt.rcParams.update(_ORIGINAL_PARAMS)
    plt.switch_backend(_ORIGINAL_BACKEND)
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_defaults(self):
        with patch('matplotlib.rcParams.update') as mock_update, \
                patch('matplotlib.pyplot.switch_backend') as mock_switch:
            lp.latexify()

            mock_update.assert_called_once_with(lp.PARAMS)
            mock_switch.assert_called_once_with('pgf')
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_custom_params(self):
        with patch('matplotlib.rcParams.update') as mock_update, \
                patch('matplotlib.pyplot.switch_backend') as mock_switch:
            params = {'param_a': 1, 'param_b': 2}
            lp.latexify(params)

            mock_update.assert_called_once_with(params)
            mock_switch.assert_called_once_with('pgf')
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_raises_error_on_bad_backend(self):
        with patch('matplotlib.rcParams.update') as mock_update:
            with pytest.raises(ValueError):
                lp.latexify(new_backend='foo')

            mock_update.assert_called_once_with(lp.PARAMS)
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_revert():
    with patch('matplotlib.rcParams.update') as mock_update, \
            patch('matplotlib.pyplot.switch_backend') as mock_switch:
        lp.latexify()
        lp.revert()
        mock_update.assert_called_with(dict(plt.rcParams))
        mock_switch.assert_called_with(plt.get_backend())
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_defaults(self):
        with patch('matplotlib.rcParams.update') as mock_update, \
                patch('matplotlib.pyplot.switch_backend') as mock_switch:
            old_params = dict(plt.rcParams)
            with lp.temp_params():
                mock_update.assert_called_with(old_params)
            mock_update.assert_called_with(old_params)
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_font_size(self):
        with patch('matplotlib.rcParams.update') as mock_update, \
                patch('matplotlib.pyplot.switch_backend') as mock_switch:
            old_params = dict(plt.rcParams)
            with lp.temp_params(font_size=10):
                called_with = mock_update.call_args[0][0]
                print(called_with)
                assert all(called_with[k] == 10
                           for k in lp.PARAMS if 'size' in k)
            mock_update.assert_called_with(old_params)
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def test_params_dict(self):
        with patch('matplotlib.rcParams.update') as mock_update, \
                patch('matplotlib.pyplot.switch_backend') as mock_switch:
            old_params = dict(plt.rcParams)
            with lp.temp_params(params_dict={'font.family': 'sans-serif'}):
                called_with = mock_update.call_args[0][0]
                assert called_with['font.family'] == 'sans-serif'
            mock_update.assert_called_with(old_params)
项目:compresso    作者:VCG    | 项目源码 | 文件源码
def adj_fig_size(width=10, height=10):
        '''Adjust figsize of plot
        '''

        fig_size = plt.rcParams["figure.figsize"]
        fig_size[0] = width
        fig_size[1] = height
        plt.rcParams["figure.figsize"] = fig_size
项目:enet-keras    作者:PavlosMelissinos    | 项目源码 | 文件源码
def run(self):
        model = self.model()
        dataset = self.dataset()
        for image_batch, target_batch in dataset.flow():
            image_batch = image_batch['image']
            target_batch = target_batch['output']
            for image, target in zip(image_batch, target_batch):
                output = model.predict(np.expand_dims(image, axis=0))[0]
                output = np.reshape(np.argmax(output, axis=-1), newshape=(512, 512))

                target = np.reshape(np.argmax(target, axis=-1), newshape=(512, 512))

                plt.rcParams["figure.figsize"] = [4 * 3, 4]

                fig = plt.figure()

                subplot1 = fig.add_subplot(131)
                subplot1.imshow(image.astype(np.uint8))
                subplot1.set_title('rgb image')
                subplot1.axis('off')

                subplot2 = fig.add_subplot(132)
                subplot2.imshow(output, cmap='gray')
                subplot2.set_title('Prediction')
                subplot2.axis('off')

                subplot3 = fig.add_subplot(133)
                masked = np.array(target)
                masked[target == 0] = 0
                subplot3.imshow(masked, cmap='gray')
                subplot3.set_title('Targets')
                subplot3.axis('off')

                fig.tight_layout()
                plt.show()
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff()
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def _finalize_plotting(self):
        pyplot.ion()
        pyplot.draw()  # update "screen"
        pyplot.show()  # show figure
        # matplotlib.interactive(interactive_status)
        pyplot.rcParams['font.size'] = self.original_fontsize
项目:tf-image-segmentation    作者:VittalP    | 项目源码 | 文件源码
def _discrete_matshow_adaptive(data, labels_names=[], title=""):
    """Displays segmentation results using colormap that is adapted
    to a number of classes. Uses labels_names to write class names
    aside the color label. Used as a helper function for 
    visualize_segmentation_adaptive() function.

    Parameters
    ----------
    data : 2d numpy array (width, height)
        Array with integers representing class predictions
    labels_names : list
        List with class_names
    """

    fig_size = [7, 6]
    plt.rcParams["figure.figsize"] = fig_size

    #get discrete colormap
    cmap = plt.get_cmap('Paired', np.max(data)-np.min(data)+1)

    # set limits .5 outside true range
    mat = plt.matshow(data,
                      cmap=cmap,
                      vmin = np.min(data)-.5,
                      vmax = np.max(data)+.5)

    #tell the colorbar to tick at integers
    cax = plt.colorbar(mat,
                       ticks=np.arange(np.min(data),np.max(data)+1))

    # The names to be printed aside the colorbar
    if labels_names:
        cax.ax.set_yticklabels(labels_names)

    if title:
        plt.suptitle(title, fontsize=15, fontweight='bold')

    plt.show()
项目:bark    作者:kylerbrown    | 项目源码 | 文件源码
def kill_shortcuts(plt):
    plt.rcParams['keymap.all_axes'] = ''
    plt.rcParams['keymap.back'] = ''
    plt.rcParams['keymap.forward'] = ''
    plt.rcParams['keymap.fullscreen'] = ''
    plt.rcParams['keymap.grid'] = ''
    plt.rcParams['keymap.home'] = ''
    plt.rcParams['keymap.pan'] = ''
    #plt.rcParams['keymap.quit'] = ''
    plt.rcParams['keymap.save'] = ''
    plt.rcParams['keymap.xscale'] = ''
    plt.rcParams['keymap.yscale'] = ''
    plt.rcParams['keymap.zoom'] = ''
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def niceFigure():
    rcParams.update({'figure.autolayout': True})
    # plt.rc('text', usetex=True)
    # plt.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    rcParams['xtick.direction'] = 'out'
    rcParams['ytick.direction'] = 'out'
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff()
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
def _finalize_plotting(self):
        pyplot.ion()
        pyplot.draw()  # update "screen"
        pyplot.show()  # show figure
        # matplotlib.interactive(interactive_status)
        pyplot.rcParams['font.size'] = self.original_fontsize
项目:tda-image-analysis    作者:rachellevanger    | 项目源码 | 文件源码
def plot_defect_classifications(bmp, list_of_classified_defects, unclassified_defect_region, td_classify, defect_free_region):

  plt.rcParams['figure.figsize'] = (10.0, 10.0);
  plt.set_cmap('gray');

  fig = plt.figure();
  ax = fig.add_subplot(111);
  fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None);

  # Plot the labeled defect regions on top of the temperature field
  bmp[defect_free_region==1.] = 0.5*bmp[defect_free_region==1.] # Defect-free region

  txt_out = []
  for defect in list_of_classified_defects:
      defect_center = centroid(defect['defect_region'])
      outline = defect['defect_region'] ^ morphology.binary_dilation(defect['defect_region'],morphology.disk(2))
      bmp[outline==1] = 255
      txt = ax.annotate(DEFECT_TYPES[defect['defect_type']],(defect_center[0]-5,defect_center[1]), color='white', fontweight='bold', fontsize=10);
      txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='k')]);
      txt_out.append(txt)

  unknown_td = np.multiply(unclassified_defect_region, (td_classify != 0).astype(np.int))
  bmp[morphology.binary_dilation(unknown_td,morphology.disk(2))==1] = 0
  bmp[morphology.binary_dilation(unknown_td,morphology.disk(1))==1] = 255

  frame = ax.imshow(bmp);

  ax.axis('off');

  return fig, ax, frame, txt_out
项目:GeHG    作者:livibetter    | 项目源码 | 文件源码
def main():

    init_figure_params()
    parser = argparse.ArgumentParser(description=__description__)
    parser.add_argument('-f', nargs='+', default=['all'], dest='figures',
                        choices=['all'] + list(FIGURE_PARAMS.keys()),
                        help='figures to generate (default %(default)s)')
    parser.add_argument('-W', '--width', type=int, default=DEFAULT_WIDTH,
                        help='width of figures (default: %(default)s)')
    parser.add_argument('-H', '--height', type=int, default=DEFAULT_HEIGHT,
                        help='height of figures (default: %(default)s)')
    parser.add_argument('-S', '--noshow', action='store_true',
                        help='do not show figures')
    parser.add_argument('-s', '--figsave', action='store_true',
                        help='save figures as images')
    parser.add_argument('-t', '--saveto', default='/tmp',
                        help='where to save images (default: %(default)s)')
    parser.add_argument('-n', '--name', default=platform.uname().node,
                        help=('name for identification '
                              '(default network name: %(default)s)'))
    parser.add_argument('csvfile', nargs='?', type=open, default=DEFAULT_CSV)
    args = parser.parse_args()

    if 'all' in args.figures:
        args.figures = list(FIGURE_PARAMS.keys())
    args.saveto = args.saveto.rstrip('/')

    emerges = read_emerges(args.csvfile)
    bins = bin_data(emerges)
    aggs = agg_data(bins, args.figures)

    dpi = plt.rcParams['figure.dpi']
    plt.rcParams['savefig.dpi'] = dpi
    plt.rcParams["figure.figsize"] = (args.width / dpi, args.height / dpi)

    plot_graphs(aggs, args)
项目:temci    作者:parttimenerd    | 项目源码 | 文件源码
def _set_fig_size(self, size: int):
        import matplotlib.pyplot as plt
        plt.rcParams['figure.figsize'] = (size, size)
        self._current_size = size
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff()
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
def _finalize_plotting(self):
        pyplot.ion()
        pyplot.draw()  # update "screen"
        pyplot.show()  # show figure
        # matplotlib.interactive(interactive_status)
        pyplot.rcParams['font.size'] = self.original_fontsize
项目:order    作者:ipudu    | 项目源码 | 文件源码
def plot_distribution(self):
        """plot distribution"""

        #plot setting
        #plt.rcParams['font.family'] = 'serif'
        #plt.rcParams['font.serif'] = 'Ubuntu'
        #plt.rcParams['font.monospace'] = 'Ubuntu Mono'
        plt.rcParams['font.size'] = 10
        plt.rcParams['axes.labelsize'] = 10
        #plt.rcParams['axes.labelweight'] = 'bold'
        plt.rcParams['xtick.labelsize'] = 8
        plt.rcParams['ytick.labelsize'] = 8
        plt.rcParams['legend.fontsize'] = 10
        plt.rcParams['figure.titlesize'] = 12

        #clean last plot
        plt.clf()

        if self.taskname == 'oto':
            plt.xlabel("Q")
            plt.ylabel(r"$P(Q)  (arb. unit)$")

        if self.taskname == 'tto':
            plt.xlabel("Sk")
            plt.ylabel(r"$P(Sk)  (arb. unit)$")

        if self.taskname == 'avc':
            plt.xlabel("Asphericity")
            plt.ylabel(r"$P(Asphericity)  (arb. unit)$")

        if self.taskname == 'msd':
            plt.xlabel('t')
            plt.ylabel('<r^2>')

        x = self.data[:,0]
        y = self.data[:,1]

        plt.plot(x,y,linewidth=2.0)

        figure = self.fprefix + '_' + self.taskname.upper() + '.pdf'
        plt.savefig(figure, bbox_inches="tight")
项目:sk-torch    作者:mattHawthorn    | 项目源码 | 文件源码
def plot_training_loss(self, training_losses: List[float], validation_losses: Opt[List[float]]=None,
                           loss_name: Opt[str]=None, model_name: Opt[str]=None,
                           title: Opt[str]=None, training_marker: str='bo--', validation_marker: str='ro--',
                           ylim: Opt[Tuple[float, float]]=None,
                           return_fig: bool=True):
        """Plot training and validation losses as would be returned by a .fit*(...) call.
        Pass optional title, markers, loss function name and model name for customization.
        If return_fig is True (default), the figure object is returned for further customization, saving to a file,
        etc., otherwise the plot is displayed and nothing is returned."""
        try:
            from matplotlib import pyplot as plt
        except Exception as e:
            raise e
        else:
            plt.rcParams['figure.figsize'] = 8, 8
            fig, ax = plt.subplots()
            loss_name = loss_name or self.loss_func.__class__.__name__
            model_name = model_name or self.torch_module.__class__.__name__
            x = list(range(1, len(training_losses) + 1))
            ax.plot(x, training_losses, training_marker, label="training {}".format(loss_name))
            if validation_losses is not None:
                ax.plot(x, validation_losses, validation_marker, label="validation {}".format(loss_name))
            ax.set_title(title or "{} {} per sample by training epoch".format(model_name, loss_name))
            ax.set_xlabel("epoch")
            ax.set_ylabel(loss_name)
            ax.set_xticks(x)
            ax.legend(loc=1)
            if ylim is not None:
                ax.set_ylim(*ylim)
            if return_fig:
                plt.show(fig)
            else:
                return fig
项目:inception-face-shape-classifier    作者:adonistio    | 项目源码 | 文件源码
def plot_images(image, Caption1):

    #plt.close()

    plt.rcParams['text.usetex'] = False
    plt.rcParams['font.size'] = 10
    plt.rcParams['font.family'] = 'Arial'

    fig, ax = plt.subplots(1, 1)
    ax.imshow(image)
    xlabel = Caption1
    ax.set_xlabel(xlabel)
    ax.set_xticks([])
    ax.set_yticks([])
    plt.show()
项目:inception-face-shape-classifier    作者:adonistio    | 项目源码 | 文件源码
def plot_images(image, Caption1):

    #plt.close()

    plt.rcParams['text.usetex'] = False
    plt.rcParams['font.size'] = 10
    plt.rcParams['font.family'] = 'Arial'

    fig, ax = plt.subplots(1, 1)
    ax.imshow(image)
    xlabel = Caption1
    ax.set_xlabel(xlabel)
    ax.set_xticks([])
    ax.set_yticks([])
    plt.show()
项目:fcn    作者:ilovin    | 项目源码 | 文件源码
def _discrete_matshow_adaptive(data, labels_names=[], title=""):
    """Displays segmentation results using colormap that is adapted
    to a number of classes. Uses labels_names to write class names
    aside the color label. Used as a helper function for 
    visualize_segmentation_adaptive() function.

    Parameters
    ----------
    data : 2d numpy array (width, height)
        Array with integers representing class predictions
    labels_names : list
        List with class_names
    """

    fig_size = [7, 6]
    plt.rcParams["figure.figsize"] = fig_size

    #get discrete colormap
    cmap = plt.get_cmap('Paired', np.max(data)-np.min(data)+1)

    # set limits .5 outside true range
    mat = plt.matshow(data,
                      cmap=cmap,
                      vmin = np.min(data)-.5,
                      vmax = np.max(data)+.5)

    #tell the colorbar to tick at integers
    cax = plt.colorbar(mat,
                       ticks=np.arange(np.min(data),np.max(data)+1))

    # The names to be printed aside the colorbar
    if labels_names:
        cax.ax.set_yticklabels(labels_names)

    if title:
        plt.suptitle(title, fontsize=15, fontweight='bold')

    plt.show()
项目:ptreeopt    作者:jdherman    | 项目源码 | 文件源码
def init_plotting():
  sns.set_style('whitegrid')

  sns.set_style('whitegrid')
  plt.rcParams['figure.figsize'] = (12, 8)
  plt.rcParams['font.size'] = 13
  plt.rcParams['font.family'] = 'OfficinaSanITCBoo'
  # plt.rcParams['font.weight'] = 'bold'
  plt.rcParams['axes.labelsize'] = 1.1*plt.rcParams['font.size']
  plt.rcParams['axes.titlesize'] = 1.1*plt.rcParams['font.size']
  plt.rcParams['legend.fontsize'] = plt.rcParams['font.size']
  plt.rcParams['xtick.labelsize'] = plt.rcParams['font.size']
  plt.rcParams['ytick.labelsize'] = plt.rcParams['font.size']