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

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

项目:pytomo3d    作者:computational-seismology    | 项目源码 | 文件源码
def reset_matplotlib():
    """
    Reset matplotlib to a common default.
    """
    # Set all default values.
    mpl.rcdefaults()
    # Force agg backend.
    plt.switch_backend('agg')
    # These settings must be hardcoded for running the comparision tests and
    # are not necessarily the default values.
    mpl.rcParams['font.family'] = 'Bitstream Vera Sans'
    mpl.rcParams['text.hinting'] = False
    # Not available for all matplotlib versions.
    try:
        mpl.rcParams['text.hinting_factor'] = 8
    except KeyError:
        pass
    import locale
    locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))


# Most generic way to get the data folder path.
项目:gconv_experiments    作者:tscohen    | 项目源码 | 文件源码
def paper_plots_p4m():
    import matplotlib
    matplotlib.rcParams['ps.useafm'] = True
    matplotlib.rcParams['pdf.use14corefonts'] = True
    matplotlib.rcParams['text.usetex'] = True

    im_e, fmaps_e = testplot_p4m(m=0, r=0)
    im_r, fmaps_r = testplot_p4m(m=0, r=1)
    im_m, fmaps_m = testplot_p4m(m=1, r=0)

    plot_p4m(fmaps_e.reshape(2, 4, 7, 7), rlabels='cayley2', fontsize=10, labelpad_factor_1=0.2,
             labelpad_factor_2=0.8, labelpad_factor_3=0.5, labelpad_factor_4=1.2,
             figsize=(2.5, 2.5), rcolor='red', mcolor='blue')
    plt.savefig('./p4m_fmap_e_mini.eps', format='eps', dpi=600)
    plot_p4m(fmaps_r.reshape(2, 4, 7, 7), rlabels='cayley2', fontsize=10, labelpad_factor_1=0.2,
             labelpad_factor_2=0.8, labelpad_factor_3=0.5, labelpad_factor_4=1.2,
             figsize=(2.5, 2.5), rcolor='red', mcolor='blue')
    plt.savefig('./p4m_fmap_r_mini.eps', format='eps', dpi=600)
    plot_p4m(fmaps_m.reshape(2, 4, 7, 7), rlabels='cayley2', fontsize=10, labelpad_factor_1=0.2,
             labelpad_factor_2=0.8, labelpad_factor_3=0.5, labelpad_factor_4=1.2,
             figsize=(2.5, 2.5), rcolor='red', mcolor='blue')
    plt.savefig('./p4m_fmap_m_mini.eps', format='eps', dpi=600)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def setup(self):
        import matplotlib
        def act_mpl(backend):
            matplotlib.rcParams['backend'] = backend

        # Save rcParams since they get modified
        self._saved_rcParams = matplotlib.rcParams
        self._saved_rcParamsOrig = matplotlib.rcParamsOrig
        matplotlib.rcParams = dict(backend='Qt4Agg')
        matplotlib.rcParamsOrig = dict(backend='Qt4Agg')

        # Mock out functions
        self._save_am = pt.activate_matplotlib
        pt.activate_matplotlib = act_mpl
        self._save_ip = pt.import_pylab
        pt.import_pylab = lambda *a,**kw:None
        self._save_cis = pt.configure_inline_support
        pt.configure_inline_support = lambda *a,**kw:None
项目:scipy-lecture-notes-zh-CN    作者:jayleicn    | 项目源码 | 文件源码
def latex2png(latex, filename, fontset='cm'):
    latex = "$%s$" % latex
    orig_fontset = rcParams['mathtext.fontset']
    rcParams['mathtext.fontset'] = fontset
    if os.path.exists(filename):
        depth = mathtext_parser.get_depth(latex, dpi=100)
    else:
        try:
            depth = mathtext_parser.to_png(filename, latex, dpi=100)
        except:
            warnings.warn("Could not render math expression %s" % latex,
                          Warning)
            depth = 0
    rcParams['mathtext.fontset'] = orig_fontset
    return depth

# LaTeX to HTML translation stuff:
项目:FA-IR_Ranking    作者:MilkaLichtblau    | 项目源码 | 文件源码
def plotFourListsInOnePlot(xdata, ydata1, ydata2, ydata3, ydata4, xlabel, ylabel, filename):
    mpl.rcParams.update({'font.size': 20, 'lines.linewidth': 3, 'lines.markersize': 15})
    # avoid type 3 (i.e. bitmap) fonts in figures
    mpl.rcParams['ps.useafm'] = True
    mpl.rcParams['pdf.use14corefonts'] = True
    mpl.rcParams['text.usetex'] = True
    plt.plot(xdata, ydata1, c='r')
    plt.scatter(xdata, ydata2, marker='x', c='r', s=100)
    plt.plot(xdata, ydata3, c='b')
    plt.scatter(xdata, ydata4, marker='x', c='b', s=100)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.grid()
    plt.tight_layout()

    if filename:
        plt.savefig(filename)
    else:
        plt.show()
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def __init__(self, canvas, num, window):
        FigureManagerBase.__init__(self, canvas, num)
        self.window = window
        self.window.withdraw()
        self.set_window_title("Figure %d" % num)
        self.canvas = canvas
        self._num =  num
        _, _, w, h = canvas.figure.bbox.bounds
        w, h = int(w), int(h)
        self.window.minsize(int(w*3/4),int(h*3/4))
        if matplotlib.rcParams['toolbar']=='classic':
            self.toolbar = NavigationToolbar( canvas, self.window )
        elif matplotlib.rcParams['toolbar']=='toolbar2':
            self.toolbar = NavigationToolbar2TkAgg( canvas, self.window )
        else:
            self.toolbar = None
        if self.toolbar is not None:
            self.toolbar.update()
        self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self._shown = False

        def notify_axes_change(fig):
            'this will be called whenever the current axes is changed'
            if self.toolbar != None: self.toolbar.update()
        self.canvas.figure.add_axobserver(notify_axes_change)
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def __init__(self, canvas, num, window):
        FigureManagerBase.__init__(self, canvas, num)
        self.window = window
        self.window.withdraw()
        self.set_window_title("Figure %d" % num)
        self.canvas = canvas
        self._num =  num
        if matplotlib.rcParams['toolbar']=='toolbar2':
            self.toolbar = NavigationToolbar2TkAgg( canvas, self.window )
        else:
            self.toolbar = None
        if self.toolbar is not None:
            self.toolbar.update()
        self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self._shown = False

        def notify_axes_change(fig):
            'this will be called whenever the current axes is changed'
            if self.toolbar != None: self.toolbar.update()
        self.canvas.figure.add_axobserver(notify_axes_change)
项目: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)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def setup(self):
        import matplotlib
        def act_mpl(backend):
            matplotlib.rcParams['backend'] = backend

        # Save rcParams since they get modified
        self._saved_rcParams = matplotlib.rcParams
        self._saved_rcParamsOrig = matplotlib.rcParamsOrig
        matplotlib.rcParams = dict(backend='Qt4Agg')
        matplotlib.rcParamsOrig = dict(backend='Qt4Agg')

        # Mock out functions
        self._save_am = pt.activate_matplotlib
        pt.activate_matplotlib = act_mpl
        self._save_ip = pt.import_pylab
        pt.import_pylab = lambda *a,**kw:None
        self._save_cis = pt.configure_inline_support
        pt.configure_inline_support = lambda *a,**kw:None
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def activate_matplotlib(backend):
    """Activate the given backend and set interactive to True."""

    import matplotlib
    matplotlib.interactive(True)

    # Matplotlib had a bug where even switch_backend could not force
    # the rcParam to update. This needs to be set *before* the module
    # magic of switch_backend().
    matplotlib.rcParams['backend'] = backend

    import matplotlib.pyplot
    matplotlib.pyplot.switch_backend(backend)

    # This must be imported last in the matplotlib series, after
    # backend/interactivity choices have been made
    import matplotlib.pyplot as plt

    plt.show._needmain = False
    # We need to detect at runtime whether show() is called by the user.
    # For this, we wrap it into a decorator which adds a 'called' flag.
    plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
项目:kernel-gof    作者:wittawatj    | 项目源码 | 文件源码
def set_default_matplotlib_options():
    # font options
    font = {
    #     'family' : 'normal',
        #'weight' : 'bold',
        'size'   : 30
    }
    matplotlib.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})


    # matplotlib.use('cairo')
    matplotlib.rc('text', usetex=True)
    matplotlib.rcParams['text.usetex'] = True
    plt.rc('font', **font)
    plt.rc('lines', linewidth=3, markersize=10)
    # matplotlib.rcParams['ps.useafm'] = True
    # matplotlib.rcParams['pdf.use14corefonts'] = True

    matplotlib.rcParams['pdf.fonttype'] = 42
    matplotlib.rcParams['ps.fonttype'] = 42
项目:opencv-helpers    作者:abarrak    | 项目源码 | 文件源码
def plot(image, is_bgr=True, cmap=None, title='Image Viewer', disable_toolbar=True):
  ''' show image in matplotlib viewer. if path is given, load() first. '''
  if isinstance(image, str):
    image = load(str)

  if disable_toolbar:
    matplotlib.rcParams['toolbar'] = 'None'

  # opencv image are in BGR colormap while matplotlib in RGB.
  if is_bgr:
    image = convert_to_rgb(image)

  fig = plt.figure()
  fig.canvas.set_window_title(title)

  plt.imshow(image, cmap)
  # hide tick values on X and Y axis.
  plt.xticks([]), plt.yticks([])
  plt.show()
项目:opencv-helpers    作者:abarrak    | 项目源码 | 文件源码
def plot_two_images(image_1, image_2, cmap_1=None, cmap_2=None, title='Image Viewer', disable_toolbar=True):
  '''
  plot :image1: and :image2: in a row.
  '''
  if disable_toolbar:
    matplotlib.rcParams['toolbar'] = 'None'

  fig = plt.figure(figsize=(13, 4))
  fig.canvas.set_window_title(title)

  a = fig.add_subplot(1, 2, 1)

  plt.imshow(image_1, cmap_1)
  plt.xticks([]), plt.yticks([])
  a.set_title('Before')

  a = fig.add_subplot(1, 2 ,2)
  plt.imshow(image_2, cmap_2)
  plt.xticks([]), plt.yticks([])
  a.set_title('After')

  plt.show()
项目:PhasePApy    作者:austinholland    | 项目源码 | 文件源码
def plot_picks(self):
    """ 
    Plot picks and waveform.
    """

    matplotlib.rcParams["axes.labelsize"]="large"
    matplotlib.rcParams["axes.linewidth"]=2.0
    matplotlib.rcParams["xtick.major.size"]=8
    matplotlib.rcParams["ytick.major.size"]=8
    matplotlib.rcParams["ytick.minor.size"]=5
    matplotlib.rcParams["xtick.labelsize"]="large"
    matplotlib.rcParams["ytick.labelsize"]="large"

    dt = self.stats.delta
    t = np.arange(0, self.stats.npts/self.stats.sampling_rate, dt) 
    scnl,picks,trigger,snr = self.pick_ident()
    fig = plt.figure(figsize=(10,5))
    plt.plot(t, self.tr, c='gray')
    for i in range(len(picks)):
      plt.plot([(picks[i]-self.tr.stats.starttime), (picks[i]-self.tr.stats.starttime)], [min(self.tr),max(self.tr)], 'k--')
      plt.text((picks[i]-self.tr.stats.starttime),max(self.tr)-0.3*(max(self.tr)-min(self.tr)),'%s' % (self.pol[i]),color='black')
    plt.xlabel('Time (s)')
    plt.show()
项目:gym-unrealcv    作者:zfw1226    | 项目源码 | 文件源码
def __init__(self, outdir, data_key='episode_rewards', line_color='blue'):
        """
        Liveplot renders a graph of either episode_rewards or episode_lengths
        Args:
            outdir (outdir): Monitor output file location used to populate the graph
            data_key (Optional[str]): The key in the json to graph (episode_rewards or episode_lengths).
            line_color (Optional[dict]): Color of the plot.
        """
        #data_key can be set to 'episode_lengths'
        self.outdir = outdir
        self._last_data = None
        self.data_key = data_key
        self.line_color = line_color

        #styling options
        matplotlib.rcParams['toolbar'] = 'None'
        plt.style.use('ggplot')
        plt.xlabel("episodes")
        plt.ylabel("cumulated episode rewards")
        fig = plt.gcf().canvas.set_window_title('averaged_simulation_graph')
        matplotlib.rcParams.update({'font.size': 15})
项目:gtfspy    作者:CxAalto    | 项目源码 | 文件源码
def plot_route_network_thumbnail(g, map_style=None):
    width = 512  # pixels
    height = 300  # pixels
    scale = 24
    dpi = mpl.rcParams["figure.dpi"]

    width_m = width * scale
    height_m = height * scale
    median_lat, median_lon = get_median_lat_lon_of_stops(g)
    dlat = util.wgs84_height(height_m)
    dlon = util.wgs84_width(width_m, median_lat)
    spatial_bounds = {
        "lon_min": median_lon - dlon,
        "lon_max": median_lon + dlon,
        "lat_min": median_lat - dlat,
        "lat_max": median_lat + dlat
    }
    fig = plt.figure(figsize=(width/dpi, height/dpi))
    ax = fig.add_subplot(111)
    plt.subplots_adjust(bottom=0.0, left=0.0, right=1.0, top=1.0)
    return plot_route_network_from_gtfs(g, ax, spatial_bounds, map_alpha=1.0, scalebar=False, legend=False, map_style=map_style)
项目:scanpy    作者:theislab    | 项目源码 | 文件源码
def set_figure_params(dpi=None, figure_formats=['png2x']):
    """Set resolution and format of figures.

    Parameters
    ----------
    dpi : int, optional
        Resolution of png output in dots per inch.
    figure_formats : list of strings
        Only concerns the IPython environment; see
        `IPython.core.display.set_matplotlib_formats` for more details. For
        setting the default format for saving figures, directly set
        `file_format_figs`.
    """
    try:
        import IPython
        IPython.core.display.set_matplotlib_formats(*figure_formats)
    except:
        pass
    from matplotlib import rcParams
    global _dpi
    if dpi is not None: _dpi = dpi
    # need to set the following two lines as older Jupyter notebooks seem to use
    # 'savefig.dpi' and more rescent ones 'figure.dpi'
    rcParams['savefig.dpi'] = _dpi
    rcParams['figure.dpi'] = _dpi
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
def figure_nobar(*args, **kwargs):
    """Make matplotlib figure with no toolbar"""
    from matplotlib import rcParams, pyplot as plt
    old_val = rcParams['toolbar']
    try:
        rcParams['toolbar'] = 'none'
        fig = plt.figure(*args, **kwargs)
        # remove button press catchers (for toolbar)
        cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys())
        for key in cbs:
            fig.canvas.callbacks.disconnect(key)
    except Exception as ex:
        raise ex
    finally:
        rcParams['toolbar'] = old_val
    return fig
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def setup(self):
        import matplotlib
        def act_mpl(backend):
            matplotlib.rcParams['backend'] = backend

        # Save rcParams since they get modified
        self._saved_rcParams = matplotlib.rcParams
        self._saved_rcParamsOrig = matplotlib.rcParamsOrig
        matplotlib.rcParams = dict(backend='Qt4Agg')
        matplotlib.rcParamsOrig = dict(backend='Qt4Agg')

        # Mock out functions
        self._save_am = pt.activate_matplotlib
        pt.activate_matplotlib = act_mpl
        self._save_ip = pt.import_pylab
        pt.import_pylab = lambda *a,**kw:None
        self._save_cis = pt.configure_inline_support
        pt.configure_inline_support = lambda *a,**kw:None
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def activate_matplotlib(backend):
    """Activate the given backend and set interactive to True."""

    import matplotlib
    matplotlib.interactive(True)

    # Matplotlib had a bug where even switch_backend could not force
    # the rcParam to update. This needs to be set *before* the module
    # magic of switch_backend().
    matplotlib.rcParams['backend'] = backend

    import matplotlib.pyplot
    matplotlib.pyplot.switch_backend(backend)

    # This must be imported last in the matplotlib series, after
    # backend/interactivity choices have been made
    import matplotlib.pylab as pylab

    pylab.show._needmain = False
    # We need to detect at runtime whether show() is called by the user.
    # For this, we wrap it into a decorator which adds a 'called' flag.
    pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
项目:gym-adv    作者:lerrel    | 项目源码 | 文件源码
def __init__(self, outdir, data_key='episode_rewards', line_color='blue'):
        """
        Liveplot renders a graph of either episode_rewards or episode_lengths

        Args:
            outdir (outdir): Monitor output file location used to populate the graph
            data_key (Optional[str]): The key in the json to graph (episode_rewards or episode_lengths).
            line_color (Optional[dict]): Color of the plot.
        """
        self.outdir = outdir
        self._last_data = None
        self.data_key = data_key
        self.line_color = line_color

        #styling options
        matplotlib.rcParams['toolbar'] = 'None'
        plt.style.use('ggplot')
        plt.xlabel("")
        plt.ylabel(data_key)
        fig = plt.gcf().canvas.set_window_title('')
项目:githubgraph    作者:0x0FFF    | 项目源码 | 文件源码
def writevideo(self):
        #print animation.writers.list()
        #matplotlib.rcParams['animation.ffmpeg_args'] = ['-report', '/tmp/ffmpeg.log']
        #FFMpegWriter = animation.writers['ffmpeg']
        metadata = dict(title='Github Data Projects', artist='0x0FFF',
                        comment='Evolution of open source data projects')
        writer = FFMpegWriter(fps=30,
                              bitrate=8000,
                              metadata=metadata
                             )
        i = 0
        #self.iters = 200
        with writer.saving(self.fig, "/projects/personal/writer_test.mp4", 120):
            while i < self.iters:
                self.update_animation(i)
                writer.grab_frame()
                i += 1
        return
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def setup(self):
        import matplotlib
        def act_mpl(backend):
            matplotlib.rcParams['backend'] = backend

        # Save rcParams since they get modified
        self._saved_rcParams = matplotlib.rcParams
        self._saved_rcParamsOrig = matplotlib.rcParamsOrig
        matplotlib.rcParams = dict(backend='Qt4Agg')
        matplotlib.rcParamsOrig = dict(backend='Qt4Agg')

        # Mock out functions
        self._save_am = pt.activate_matplotlib
        pt.activate_matplotlib = act_mpl
        self._save_ip = pt.import_pylab
        pt.import_pylab = lambda *a,**kw:None
        self._save_cis = pt.configure_inline_support
        pt.configure_inline_support = lambda *a,**kw:None
项目: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')

    # ????????????
项目:extract    作者:dblalock    | 项目源码 | 文件源码
def makeDatasetsFig():
    mpl.rcParams['axes.titlesize'] = 32
    mpl.rcParams['axes.titleweight'] = 'bold'
    mpl.rcParams['axes.facecolor'] = AXES_BG_COLOR

    fig, axes = plt.subplots(2, 2)
    axes = axes.flatten()

    makeDishwasherFig(axes[0], save=False)
    makeTidigitsFig(axes[1], save=False)
    makeMsrcFig(axes[2], save=False)
    makeUcrFig(axes[3], save=False)

    plt.tight_layout(h_pad=2.)
    saveFigWithName('datasets')


# ================================================================ Fig1
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        # Use smaller labels
        rcParams['axes.labelsize'] = 'small'
        rcParams['xtick.labelsize'] = 'small'
        rcParams['ytick.labelsize'] = 'small'
        self.axes = fig.add_axes([0.15, 0.15, 0.85, 0.85])
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.setFocus()
        fig.patch.set_alpha(0)
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def resizeEvent(self, event):
        w = event.size().width()
        h = event.size().height()
        # Leave a fixed amount for the axes
        padding = 7.5*FontProperties(size=rcParams['axes.labelsize']).get_size_in_points()
        posx = padding/w
        posy = padding/h
        self.axes.set_position([posx, posy, 0.97-posx, 0.97-posy])
        super(MplCanvas, self).resizeEvent(event)
项目:bob.bio.base    作者:bioidiap    | 项目源码 | 文件源码
def _plot_det(dets, colors, labels, title, fontsize=10, position=None):
  if position is None: position = 'upper right'
  # open new page for current plot
  figure = pyplot.figure(figsize=(matplotlib.rcParams['figure.figsize'][0],
                                  matplotlib.rcParams['figure.figsize'][0] * 0.975))
  pyplot.grid(True)

  # plot the DET curves
  for i in range(len(dets)):
    pyplot.plot(dets[i][0], dets[i][1], color=colors[i], label=labels[i])

  # change axes accordingly
  det_list = [0.0002, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.7, 0.9, 0.95]
  ticks = [bob.measure.ppndf(d) for d in det_list]
  labels = [("%.5f" % d).rstrip('0').rstrip('.') for d in det_list]
  pyplot.xticks(ticks, [l if i % 2 else "" for i,l in enumerate(labels)])
  pyplot.yticks(ticks, labels)
  pyplot.axis((ticks[0], ticks[-1], ticks[0], ticks[-1]))

  pyplot.xlabel('FMR')
  pyplot.ylabel('FNMR')
  pyplot.legend(loc=position, prop = {'size':fontsize})
  pyplot.title(title)

  return figure
项目:circletracking    作者:caspervdw    | 项目源码 | 文件源码
def imshow(image, ax=None, mpp=1., origin=(0, 0), ax_labels=False, **kwargs):
    """Show an image. Origin is in pixels."""
    _imshow_style = dict(origin='lower', interpolation='nearest',
                         cmap=plt.cm.gray, aspect='equal')
    _imshow_style.update(kwargs)
    if not is_rgb(image, ndim=2):
        try:
            from pims import to_rgb
        except ImportError:
            raise ImportError("Imshow requires PIMS to display a non-RGB image")
        image = to_rgb(image, kwargs.pop('colors', None), normed=False) / 255.
    shape = image.shape[:2]
    mpp = validate_tuple(mpp, ndim=2)
    origin = validate_tuple(origin, ndim=2)

    # extent is defined on the outer edges of the pixels
    # we want the center of the topleft to intersect with the origin
    extent = [(origin[1] - 0.5) * mpp[1],
              (origin[1] + shape[1] - 0.5) * mpp[1],
              (origin[0] - 0.5) * mpp[0],
              (origin[0] + shape[0] - 0.5) * mpp[0]]

    ax.imshow(image, extent=extent, **_imshow_style)
    ax.set_xlim(extent[0], extent[1])
    ax.set_ylim(extent[3], extent[2])

    if ax_labels:
        if mpp == 1.:
            fmt = '{} [px]'
        elif mpl.rcParams['text.usetex']:
            fmt = r'{} [\textmu m]'
        else:
            fmt = r'{} [\xb5m]'
        ax.set_xlabel(fmt.format('x'))
        ax.set_ylabel(fmt.format('y'))
    return ax
项目:Recruit    作者:Weiyanyu    | 项目源码 | 文件源码
def generateImage(self, sourceName, fileName, image_kind):
        matplotlib.rcParams['font.family'] = 'SimHei'           #???????linux?????
        matplotlib.rc('font', **self.FONT)               
        mydata = pd.read_csv(self.FILE_PATH + sourceName)       
        mydata.sort_index()

        if image_kind == 'pie':
            mydata.plot(kind='pie', subplots=True, figsize=(10,10), autopct='%1.1f%%', fontsize=20)
        elif image_kind == 'bar':
            mydata.plot(kind='bar', subplots=True, fontsize=10, figsize=(4,6))
        else:
            raise TypeError('????')

        plt.savefig(self.FILE_PATH + 'images/' + fileName,dpi=100)
        plt.close()
项目:ml_capstone    作者:drscott173    | 项目源码 | 文件源码
def __init__(self, name='q_value', track=False):
        # Tf graph input
        self.ai = Learner(True)
        self.saver = tf.train.Saver()
        self.saver.restore(self.ai.s,"models/narrow-deep-pipe.ckpt")
        self.theta = 0
        self.im = None
        self.fig = None
        self.sensor = 0
        self.smoothing = True
        matplotlib.rcParams['xtick.direction'] = 'out'
        matplotlib.rcParams['ytick.direction'] = 'out'
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def DipoleDipolefun(i):
    matplotlib.rcParams['font.size'] = 14
    plt.figure(figsize=(10, 3))
    ntx = xr.size-2
    plt.plot(xr[:-1]+dxr*0.5, np.zeros_like(xr[:-1]), 'ko')
    plt.plot(xr[i]+dxr[i]*0.5, np.zeros(1), 'ro')
    # for i in range(ntx):
    if i < ntx-nmax+1:
        txmid = xr[i]+dxr[i]*0.5
        rxmid = xr[i+1:i+1+nmax]+dxr[i+1:i+1+nmax]*0.5
        mid = (txmid+rxmid)*0.5
        plt.plot(rxmid, np.zeros(rxmid.size), 'go')
        plt.plot(mid, np.arange(nmax)+1., 'bo')
        plt.plot(np.r_[txmid, mid[-1]], np.r_[0, nmax], 'k:')
        for j in range(nmax):
            plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')

    else:
        txmid = xr[i]+dxr[i]*0.5
        rxmid = xr[i+1:ntx+1]+dxr[i+1:ntx+1]*0.5
        mid = (txmid+rxmid)*0.5
        plt.plot((txmid+rxmid)*0.5, np.arange(mid.size)+1., 'bo')
        plt.plot(rxmid, np.zeros(rxmid.size), 'go')
        plt.plot(np.r_[txmid, mid[-1]], np.r_[0, mid.size], 'k:')
        for j in range(ntx-i):
            plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')
    plt.xlabel("X (m)")
    plt.ylabel("N-spacing")
    plt.xlim(xr.min(), xr.max())
    plt.ylim(nmax+1, -1)
    plt.show()
    return
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def DipoleDipolefun(i):
    """
    Plotting function to display all receivers and pseudolocations
    of a dipole-dipole survey for each source i

    :param int i: source index
    """
    matplotlib.rcParams['font.size'] = 14
    plt.figure(figsize=(10, 3))
    nmax = 8
    xr = np.linspace(-40, 40, 20)
    ntx = xr.size-2
    dxr = np.diff(xr)
    plt.plot(xr[:-1]+dxr*0.5, np.zeros_like(xr[:-1]), 'ko')
    plt.plot(xr[i]+dxr[i]*0.5, np.zeros(1), 'ro')
    # for i in range(ntx):
    if i < ntx-nmax+1:
        txmid = xr[i]+dxr[i]*0.5
        rxmid = xr[i+1:i+1+nmax]+dxr[i+1:i+1+nmax]*0.5
        mid = (txmid+rxmid)*0.5
        plt.plot(rxmid, np.zeros(rxmid.size), 'go')
        plt.plot(mid, np.arange(nmax)+1., 'bo')
        plt.plot(np.r_[txmid, mid[-1]], np.r_[0, nmax], 'k:')
        for j in range(nmax):
            plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')

    else:
        txmid = xr[i]+dxr[i]*0.5
        rxmid = xr[i+1:ntx+1]+dxr[i+1:ntx+1]*0.5
        mid = (txmid+rxmid)*0.5
        plt.plot((txmid+rxmid)*0.5, np.arange(mid.size)+1., 'bo')
        plt.plot(rxmid, np.zeros(rxmid.size), 'go')
        plt.plot(np.r_[txmid, mid[-1]], np.r_[0, mid.size], 'k:')
        for j in range(ntx-i):
            plt.plot(np.r_[rxmid[j], mid[j]], np.r_[0, j+1], 'k:')
    plt.xlabel("X (m)")
    plt.ylabel("N-spacing")
    plt.xlim(xr.min(), xr.max())
    plt.ylim(nmax+1, -1)
    plt.show()
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def _setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    try:
        locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
    except locale.Error:
        try:
            locale.setlocale(locale.LC_ALL, str('English_United States.1252'))
        except locale.Error:
            warnings.warn(
                "Could not set locale to English/United States. "
                "Some date-related tests may fail")

    plt.switch_backend('Agg')  # use Agg backend for these test
    if mpl.get_backend().lower() != "agg":
        msg = ("Using a wrong matplotlib backend ({0}), "
               "which will not produce proper images")
        raise Exception(msg.format(mpl.get_backend()))

    # These settings *must* be hardcoded for running the comparison
    # tests
    mpl.rcdefaults()  # Start with all defaults
    mpl.rcParams['text.hinting'] = True
    mpl.rcParams['text.antialiased'] = True
    mpl.rcParams['text.hinting_factor'] = 8

    # make sure we don't carry over bad plots from former tests
    msg = ("no of open figs: {} -> find the last test with ' "
           "python tests.py -v' and add a '@cleanup' decorator.")
    assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
项目:wiicop    作者:barnabuskev    | 项目源码 | 文件源码
def __init__(self,aqc_info,BB_X,BB_Y):
        self.acq_info = aqc_info
        # Initial instructions
        self.text_start = 'Press Spacebar to start recording'
        self.text_stop = 'Press Spacebar to stop recording'
        # remove toolbar
        mpl.rcParams['toolbar'] = 'None'
        # Create new figure and an axes which fills it...
        # set figure width in inches
        fig_width = 12
        # set fig ratio based on size of bboard rectange whose corners are sensors
        self.fig = plt.figure(figsize=(fig_width, fig_width*BB_Y/BB_X))
        self.fig.canvas.set_window_title(aqc_name(self.acq_info))
        # frameon determines whether background of frame will be drawn
        ax = self.fig.add_axes([0, 0, 1, 1], frameon=False)
        ax.set_xlim(-BB_X/2, BB_X/2), ax.set_xticks([])
        ax.set_ylim(-BB_Y/2, BB_Y/2), ax.set_yticks([])
        # create a scatter object at initial position 0,0
        self.scat = ax.scatter(0, 0, s=200, lw=0.5, facecolors='green')
        # create text box
        self.text_h = ax.text(0.02, 0.98, self.text_start, verticalalignment='top',horizontalalignment='left',
        transform=ax.transAxes, fontsize=12, bbox=dict(facecolor='white'), gid = 'notrec')
        # create timer object
        if self.acq_info['acq_time'] != 'inf':
            acq_time_ms = int(self.acq_info['acq_time'])*1000
            self.acq_timer = self.fig.canvas.new_timer(interval=acq_time_ms)
            self.acq_timer.add_callback(self.t_event)
        # attach keypress event handler to figure canvas
        self.fig.canvas.mpl_connect('key_press_event', self.onkeypress)
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def resetplot():
    import matplotlib
    import pylab as plt
    kw = {}
    for p in ['bottom', 'top', 'left', 'right', 'hspace', 'wspace']:
        kw[p] = matplotlib.rcParams['figure.subplot.' + p]
    plt.subplots_adjust(**kw)
项目:electrostatics    作者:tomduck    | 项目源码 | 文件源码
def plot(self, linewidth=None, startarrows=True, endarrows=True):
        """Plots the field line and arrows."""

        if linewidth == None:
            linewidth = matplotlib.rcParams['lines.linewidth']

        x, y = zip(*self.x)
        pyplot.plot(x, y, '-k', linewidth=linewidth)

        n = int(len(x)/2) if len(x) < 225 else 75
        if startarrows:
            pyplot.arrow(x[n], y[n], (x[n+1]-x[n])/100., (y[n+1]-y[n])/100.,
                         fc="k", ec="k",
                         head_width=0.1*linewidth, head_length=0.1*linewidth)

        if len(x) < 225 or not endarrows:
            return

        pyplot.arrow(x[-n], y[-n],
                     (x[-n+1]-x[-n])/100., (y[-n+1]-y[-n])/100.,
                     fc="k", ec="k",
                     head_width=0.1*linewidth, head_length=0.1*linewidth)
项目:prince    作者:MaxHalford    | 项目源码 | 文件源码
def __init__(self):

        mpl.rcParams['figure.figsize'] = (9.6, 7.2)

        mpl.rcParams['lines.linewidth'] = 1.8 # line width in points
        mpl.rcParams['lines.markeredgewidth'] = 0.3 # the line width around the marker symbol
        mpl.rcParams['lines.markersize'] = 7  # markersize, in points

        mpl.rcParams['grid.alpha'] = 0.5 # transparency, between 0.0 and 1.0
        mpl.rcParams['grid.linestyle'] = '-' # simple line
        mpl.rcParams['grid.linewidth'] = 0.4 # in points
项目:gconv_experiments    作者:tscohen    | 项目源码 | 文件源码
def paper_plots_p4():
    import matplotlib
    matplotlib.rcParams['ps.useafm'] = True
    matplotlib.rcParams['pdf.use14corefonts'] = True
    matplotlib.rcParams['text.usetex'] = True

    im_e, fmaps_e = testplot_p4(r=0)
    im_r, fmaps_r = testplot_p4(r=1)

    plot_p4(fmaps_e, fontsize=10, labelpad_factor_1=.3, labelpad_factor_2=.6, figsize=(1.6, 1.6))
    plt.savefig('./p4_fmap_e_mini.eps', format='eps', dpi=600)
    plot_p4(fmaps_r, fontsize=10, labelpad_factor_1=.3, labelpad_factor_2=.6, figsize=(1.6, 1.6))
    plt.savefig('./p4_fmap_r_mini.eps', format='eps', dpi=600)
项目:FHDMM    作者:aweinstein    | 项目源码 | 文件源码
def plot_actions(cue=0):
    mpl.rcParams['axes.labelsize'] = 'large'
    d_map = {3:1, 8:2, 14:3, 23:4}
    df = pd.read_pickle('data.pkl').reset_index()
    df = df.loc[df['cue'] == cue]
    g = sns.FacetGrid(df, col='subject',
                      col_wrap=6, size=1.5, ylim=(0, 5), aspect=1.5)

    g.map(plt.plot, 'action')
    g.set(xticks=[], yticks=[0,1,2,3], yticklabels=['3', '8', '14', '23'])
    g.set(ylim=(-0.5, 4))
    g.set_ylabels('choice')
    g.fig.tight_layout()
    g.fig.subplots_adjust(top=0.93)


    subjects = df['subject'].unique()
    for ax, subject in zip(g.axes, subjects):
        df_subject = df.loc[df['subject'] == subject]
        df_subject.reset_index(inplace=True)
        df_wins = df_subject.loc[df_subject['reward'] > 0]
        df_lose = df_subject.loc[df_subject['reward'] < 0]
        pos_win = df_wins.loc[df_wins['subject'] == subject].index
        pos_lose = df_lose.loc[df_lose['subject'] == subject].index
        ax.eventplot(pos_win, lineoffsets=3.5, linelength=0.75,
                     linewidths=0.4)
        ax.eventplot(pos_lose, lineoffsets=3.5, linelength=0.75,
                     color='r', linewidths=0.4)
    plt.tight_layout()
    plt.savefig('actions_0.pdf')
    plt.show()
    globals().update(locals())
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
def __init__(self, data_model, data_view, parent=None):
        super(BaseVisualizer, self).__init__(parent=parent)
        self._model = None
        self._view = None
        self.options = {}
        self.set_data_source(data_model, data_view)
        self.set_defaults()
        self.setup_figure()

        self.function = self.draw
        mpl.rcParams["axes.formatter.useoffset"] = "False"
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def get_color_cycle():
    if mpl_ge_150:
        cyl = mpl.rcParams['axes.prop_cycle']
        # matplotlib 1.5 verifies that axes.prop_cycle *is* a cycler
        # but no garuantee that there's a `color` key.
        # so users could have a custom rcParmas w/ no color...
        try:
            return [x['color'] for x in cyl]
        except KeyError:
            pass  # just return axes.color style below
    return mpl.rcParams['axes.color_cycle']
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def setup(context="notebook", style="ticks", palette="sweet",
        font="sans-serif", font_scale=1, rc=None):
    """Set aesthetic figure parameters.

    Each set of parameters can be set directly or temporarily, see the
    referenced functions below for more information.

    Parameters
    ----------
    context : string or dict
        Plotting context parameters, see :func:`plotting_context`
    style : string or dict
        Axes style parameters, see :func:`axes_style`
    palette : string or sequence
        Color palette, see :func:`color_palette`
    font : string
        Font family, see matplotlib font manager.
    font_scale : float, optional
        Separate scaling factor to independently scale the size of the
        font elements.
    rc : dict or None
        Dictionary of rc parameter mappings to override the above.

    """
    set_context(context, font_scale)
    set_style(style, rc={"font.family": font})
    set_palette(palette=palette)
    if rc is not None:
        mpl.rcParams.update(rc)
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def reset_defaults():
    """Restore all RC params to default settings."""
    mpl.rcParams.update(mpl.rcParamsDefault)
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def reset_orig():
    """Restore all RC params to original settings (respects custom rc)."""
    mpl.rcParams.update(_orig_rc_params)
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def set_context(context=None, font_scale=1, rc=None):
    """Set the plotting context parameters.

    This affects things like the size of the labels, lines, and other
    elements of the plot, but not the overall style. The base context
    is "notebook", and the other contexts are "paper", "talk", and "poster",
    which are version of the notebook parameters scaled by .8, 1.3, and 1.6,
    respectively.

    Parameters
    ----------
    context : dict, None, or one of {paper, notebook, talk, poster}
        A dictionary of parameters or the name of a preconfigured set.
    font_scale : float, optional
        Separate scaling factor to independently scale the size of the
        font elements.
    rc : dict, optional
        Parameter mappings to override the values in the preset seaborn
        context dictionaries. This only updates parameters that are
        considered part of the context definition.

    Examples
    --------
    >>> set_context("paper")

    >>> set_context("talk", font_scale=1.4)

    >>> set_context("talk", rc={"lines.linewidth": 2})

    See Also
    --------
    plotting_context : return a dictionary of rc parameters, or use in
                       a ``with`` statement to temporarily set the context.
    set_style : set the default parameters for figure style
    set_palette : set the default color palette for figures

    """
    context_object = plotting_context(context, font_scale, rc)
    mpl.rcParams.update(context_object)
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def __enter__(self):
        rc = mpl.rcParams
        self._orig = {k: rc[k] for k in self._keys}
        self._set(self)
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def set_palette(palette, n_colors=None, desat=None):
    """Set the matplotlib color cycle using a seaborn palette.
    Parameters
    ----------
    palette : hls | husl | matplotlib colormap | seaborn color palette
        Palette definition. Should be something that :func:`color_palette`
        can process.
    n_colors : int
        Number of colors in the cycle. The default number of colors will depend
        on the format of ``palette``, see the :func:`color_palette`
        documentation for more information.
    desat : float
        Proportion to desaturate each color by.

    Examples
    --------
    >>> set_palette("Reds")
    >>> set_palette("Set1", 8, .75)
    See Also
    --------
    color_palette : build a color palette or set the color cycle temporarily
                    in a ``with`` statement.
    set_context : set parameters to scale plot elements
    set_style : set the default parameters for figure style
    """
    colors = palettes.color_palette(palette, n_colors, desat)
    if mpl_ge_150:
        from cycler import cycler
        cyl = cycler('color', colors)
        mpl.rcParams['axes.prop_cycle'] = cyl
    else:
        mpl.rcParams["axes.color_cycle"] = list(colors)
    mpl.rcParams["patch.facecolor"] = colors[0]
项目:srnn    作者:marcofraccaro    | 项目源码 | 文件源码
def plot_results(self, plot_path=None, ylim=None):

        # Plotting parameters
        label_size = 18
        mpl.rcParams['xtick.labelsize'] = label_size
        mpl.rcParams['ytick.labelsize'] = label_size
        plot_params = dict()
        plot_params['ms'] = 10
        plot_params['linewidth'] = 3

        # Plot training bound on the perplexity
        f = plt.figure(figsize=[12, 12])
        plt.errorbar(self.epochs_eval, [self.lower_bound_train_all[i] for i in self.epochs_eval],
                     [self.lower_bound_train_all_std[i] for i in self.epochs_eval], marker='d', color='b',
                     label='Train', **plot_params)
        plt.plot(self.epochs_eval, self.lower_bound_valid_all, "-rh", label="Valid", **plot_params)
        plt.plot(self.epochs_eval, self.lower_bound_test_all, "-k^", label="Test", **plot_params)
        plt.xlabel('Epochs', fontsize=20)
        plt.grid('on')
        plt.title('ELBO', fontsize=24, y=1.01)
        plt.legend(loc="lower right", handlelength=3, fontsize=20)
        if ylim is not None:
            plt.ylim(ylim)
        if plot_path is not None:
            plt.savefig(plot_path + "_epochs.png", format='png', bbox_inches='tight', dpi=200)
        plt.close(f)

        # Plot norm of the updates
        f = plt.figure(figsize=[12, 12])
        plt.errorbar(self.epochs_eval, [self.mean_norm_all[i] for i in self.epochs_eval],
                     [self.std_norm_all[i] for i in self.epochs_eval], marker='d', color='m', **plot_params)
        plt.grid('on')
        plt.title('Norm of the updates', fontsize=24, y=1.01)
        if plot_path is not None:
            plt.savefig(plot_path + "_norm.png", format='png', bbox_inches='tight', dpi=200)
        plt.close(f)
项目:srnn    作者:marcofraccaro    | 项目源码 | 文件源码
def plot_results(self, plot_path=None, ylim=None):

        # Plotting parameters
        label_size = 18
        mpl.rcParams['xtick.labelsize'] = label_size
        mpl.rcParams['ytick.labelsize'] = label_size
        plot_params = dict()
        plot_params['ms'] = 10
        plot_params['linewidth'] = 3

        # Plot training bound on the perplexity
        f = plt.figure(figsize=[12, 12])
        plt.errorbar(self.epochs_eval, [self.elbo_seq_train_all[i] for i in self.epochs_eval],
                     [self.elbo_seq_train_all_std[i] for i in self.epochs_eval], marker='d', color='b',
                     label='Train', **plot_params)
        plt.plot(self.epochs_eval, self.elbo_seq_valid_all, "-rh", label="Valid", **plot_params)
        plt.plot(self.epochs_eval, self.elbo_seq_test_all, "-k^", label="Test", **plot_params)
        plt.xlabel('Epochs', fontsize=20)
        # plt.ylabel('log()', fontsize=20)
        plt.grid('on')
        plt.title('ELBO sequence', fontsize=24, y=1.01)
        plt.legend(loc="upper right", handlelength=3, fontsize=20)
        if ylim is not None:
            plt.ylim(ylim)
        if plot_path is not None:
            plt.savefig(plot_path + "_epochs.png", format='png', bbox_inches='tight', dpi=200)
        plt.close(f)

        # Plot norm of the updates
        f = plt.figure(figsize=[12, 12])
        plt.errorbar(self.epochs_eval, [self.mean_norm_all[i] for i in self.epochs_eval],
                     [self.std_norm_all[i] for i in self.epochs_eval], marker='d', color='m', **plot_params)
        plt.grid('on')
        plt.title('Norm of the updates', fontsize=24, y=1.01)
        if plot_path is not None:
            plt.savefig(plot_path + "_norm.png", format='png', bbox_inches='tight', dpi=200)
        plt.close(f)