コード例 #1
0
ファイル: _mpl_backend.py プロジェクト: PennyQ/glue
def set_mpl_backend():

    try:
        from qtpy import PYQT5
    except:
        # If Qt isn't available, we don't have to worry about
        # setting the backend
        return

    from matplotlib import rcParams, rcdefaults

    # standardize mpl setup
    rcdefaults()

    if PYQT5:
        rcParams['backend'] = 'Qt5Agg'
    else:
        rcParams['backend'] = 'Qt4Agg'

    # The following is a workaround for the fact that Matplotlib checks the
    # rcParams at import time, not at run-time. I have opened an issue with
    # Matplotlib here: https://github.com/matplotlib/matplotlib/issues/5513
    from matplotlib import get_backend
    from matplotlib import backends
    backends.backend = get_backend()
コード例 #2
0
ファイル: data_utils.py プロジェクト: dimmddr/roadSignsNN
def analyse_sign_frame_size_fluctuations(annotation_path, output_file):
    with open(output_file, 'w') as outp:
        raw_data = pd.read_csv(annotation_path, delimiter=';')
        outp.write("Analyse frame size fluctuations.\n")
        data = pd.DataFrame()
        data['width'] = raw_data['Lower right corner X'] - raw_data['Upper left corner X']
        data['height'] = raw_data['Lower right corner Y'] - raw_data['Upper left corner Y']
        outp.write("Minimum width = {}, minimum height = {}\n".format(data['width'].min(), data['height'].min()))
        outp.write("Maximum width = {}, maximum height = {}\n".format(data['width'].max(), data['height'].max()))

        matplotlib.rcdefaults()
        matplotlib.rcParams['font.family'] = 'fantasy'
        matplotlib.rcParams['font.fantasy'] = 'Times New Roman', 'Ubuntu', 'Arial', 'Tahoma', 'Calibri'
        matplotlib.rcParams.update({'font.size': 18})

        hist, bins = np.histogram(data['width'], bins=range(data['width'].min(), data['width'].max(), 5))
        width = 0.7 * (bins[1] - bins[0])
        center = (bins[:-1] + bins[1:]) / 2
        plt.bar(center, hist, align='center', width=width)
        plt.title("Ширина дорожных знаков")
        plt.xlabel("Ширина")
        plt.ylabel("Сколько раз встречалась")
        plt.xticks(bins, bins)
        plt.show()

        hist, bins = np.histogram(data['height'], bins=range(data['width'].min(), data['width'].max(), 5))
        width = 0.7 * (bins[1] - bins[0])
        center = (bins[:-1] + bins[1:]) / 2
        plt.bar(center, hist, align='center', width=width)
        plt.title("Высота дорожных знаков")
        plt.xlabel("Высота")
        plt.ylabel("Сколько раз встречалась")
        plt.xticks(bins, bins)
        plt.show()
コード例 #3
0
ファイル: tf_plot.py プロジェクト: TomFarley/tf_libs
def set_mpl_defaults(defaults=0):
	""" Sets defaults for future mpl plots this session
	defaults = 0: Normal mpl defaults
			 = 1: More readable
			 = 2: Publication setting """
	if defaults == 0: # matplotlib defaults
		mpl.rcdefaults()
	elif defaults == 1:
		ax_labelsize = 20
		ax_titlesize = 22
		tick_labelsize = 'large'
		major_tick = dict(size=6, width=1.5, pad=4)
		minor_tick = dict(size=3, width=1, pad=4)
		lines = dict(linewidth=2.0, markersize=8)

		mpl.rc('axes', labelsize=ax_labelsize, titlesize = ax_titlesize)

		mpl.rc('xtick', labelsize=tick_labelsize)
		mpl.rc('ytick', labelsize=tick_labelsize)

		mpl.rc('xtick.major', **major_tick)
		mpl.rc('xtick.minor', **minor_tick)

		mpl.rc('ytick.major', **major_tick)
		mpl.rc('ytick.minor', **minor_tick)

		mpl.rc('lines', **lines)

	else:
		raise ValueError('mpl defaults defaults \'%d\' not recognised' % defaults)

	return
コード例 #4
0
ファイル: qa.py プロジェクト: sbrambati/toad
 def plotMovement(self, parametersFile, targetTranslations, targetRotations):
     """
     """
     parameters = numpy.loadtxt(parametersFile)
     Vsize = len(parameters)
     vols = range(0,Vsize-1)
     translations = parameters[1:Vsize,0:3]
     rotations = parameters[1:Vsize,3:6]
     rotations = rotations / numpy.pi * 180
 
     plotdata = [(translations,'translation (mm)',targetTranslations),
                 (rotations,'rotation (degree)',targetRotations)
                 ]
 
     for data, ylabel, pngoutput in plotdata:
         matplotlib.pyplot.clf()
         px, = matplotlib.pyplot.plot(vols, data[:,0])
         py, = matplotlib.pyplot.plot(vols, data[:,1])
         pz, = matplotlib.pyplot.plot(vols, data[:,2])
         matplotlib.pyplot.xlabel('DWI volumes')
         matplotlib.pyplot.xlim([0,Vsize+10])
         matplotlib.pyplot.ylabel(ylabel)
         matplotlib.pyplot.legend([px, py, pz], ['x', 'y', 'z'])
         matplotlib.pyplot.savefig(pngoutput)
 
     matplotlib.pyplot.close()
     matplotlib.rcdefaults()
コード例 #5
0
ファイル: plotting_test.py プロジェクト: willmore/D2C
def plot_polar_subplot(fig):
    #
    # Polar demo
    #
    import pylab

    r = arange(0,1,0.001)
    theta = 2*2*pi*r

    # radar green, solid grid lines
    matplotlib.rc('grid', color='#316931', linewidth=1, linestyle='-')

    ax = fig.add_subplot(1, 2, 1, polar=True, axisbg='#d5de9c')
    ax.plot(theta, r, color='#ee8d18', lw=3)

    ax.set_title("And there was much rejoicing!", fontsize=14)
    matplotlib.rcdefaults()

    #
    # First part of the subplot demo
    #
    def f(t):
        return cos(2*pi*t) * exp(-t)

    t1 = arange(0.0, 5.0, 0.10)
    t2 = arange(0.0, 5.0, 0.02)

    A1 = fig.add_subplot(1, 2, 2)
    A1.plot(t1, f(t1), 'bo')
    A1.plot(t2, f(t2), 'k')
    A1.grid(True)

    A1.set_title('A tale of one subplot')
    A1.set_ylabel('Damped oscillation', fontsize=10)
    A1.set_xlabel('time (s)', fontsize=10)
コード例 #6
0
ファイル: _base.py プロジェクト: wright-group/WrightTools
def apply_rcparams(kind="fast"):
    """Quickly apply rcparams for given purposes.

    Parameters
    ----------
    kind: {'default', 'fast', 'publication'} (optional)
        Settings to use. Default is 'fast'.
    """
    if kind == "default":
        matplotlib.rcdefaults()
    elif kind == "fast":
        matplotlib.rcParams["text.usetex"] = False
        matplotlib.rcParams["mathtext.fontset"] = "cm"
        matplotlib.rcParams["font.family"] = "sans-serif"
        matplotlib.rcParams["font.size"] = 14
        matplotlib.rcParams["legend.edgecolor"] = "grey"
        matplotlib.rcParams["contour.negative_linestyle"] = "solid"
    elif kind == "publication":
        matplotlib.rcParams["text.usetex"] = True
        preamble = "\\usepackage[cm]{sfmath}\\usepackage{amssymb}"
        matplotlib.rcParams["text.latex.preamble"] = preamble
        matplotlib.rcParams["mathtext.fontset"] = "cm"
        matplotlib.rcParams["font.family"] = "sans-serif"
        matplotlib.rcParams["font.serif"] = "cm"
        matplotlib.rcParams["font.sans-serif"] = "cm"
        matplotlib.rcParams["font.size"] = 14
        matplotlib.rcParams["legend.edgecolor"] = "grey"
        matplotlib.rcParams["contour.negative_linestyle"] = "solid"
コード例 #7
0
ファイル: __init__.py プロジェクト: Nuevalgo/Feedbot
def setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    import locale
    import warnings
    from matplotlib.backends import backend_agg, backend_pdf, backend_svg

    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")

    use("Agg", warn=False)  # use Agg backend for these tests

    # These settings *must* be hardcoded for running the comparison
    # tests and are not necessarily the default values as specified in
    # rcsetup.py
    rcdefaults()  # Start with all defaults
    rcParams["font.family"] = "Bitstream Vera Sans"
    rcParams["text.hinting"] = False
    rcParams["text.hinting_factor"] = 8

    # Clear the font caches.  Otherwise, the hinting mode can travel
    # from one test to another.
    backend_agg.RendererAgg._fontd.clear()
    backend_pdf.RendererPdf.truetype_font_cache.clear()
    backend_svg.RendererSVG.fontd.clear()
コード例 #8
0
ファイル: test_misc.py プロジェクト: BobMcFry/pandas
    def setup_method(self, method):
        TestPlotBase.setup_method(self, method)
        import matplotlib as mpl
        mpl.rcdefaults()

        self.ts = tm.makeTimeSeries()
        self.ts.name = 'ts'
コード例 #9
0
ファイル: plot.py プロジェクト: gomes310/pyrocko
def mpl_init(fontsize=10):
    '''
    Initialize Matplotlib rc parameters Pyrocko style.

    Returns the matplotlib.pyplot module for convenience.
    '''

    import matplotlib

    matplotlib.rcdefaults()
    matplotlib.rc('font', size=fontsize)
    matplotlib.rc('axes', linewidth=1.5)
    matplotlib.rc('xtick', direction='out')
    matplotlib.rc('ytick', direction='out')
    ts = fontsize * 0.7071
    matplotlib.rc('xtick.major', size=ts, width=0.5, pad=ts)
    matplotlib.rc('ytick.major', size=ts, width=0.5, pad=ts)
    matplotlib.rc('figure', facecolor='white')

    try:
        matplotlib.rc('axes', color_cycle=[to01(x) for x in graph_colors])
    except KeyError:
        pass

    from matplotlib import pyplot as plt
    return plt
コード例 #10
0
ファイル: base.py プロジェクト: angelcalayag/obspy
    def __enter__(self):
        """
        Set matplotlib defaults.
        """
        from matplotlib import get_backend, rcParams, rcdefaults
        import locale

        try:
            locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
        except:
            try:
                locale.setlocale(locale.LC_ALL,
                                 str('English_United States.1252'))
            except:
                msg = "Could not set locale to English/United States. " + \
                      "Some date-related tests may fail"
                warnings.warn(msg)

        if get_backend().upper() != 'AGG':
            import matplotlib
            try:
                matplotlib.use('AGG', warn=False)
            except TypeError:
                msg = "Image comparison requires matplotlib backend 'AGG'"
                warnings.warn(msg)

        # set matplotlib builtin default settings for testing
        rcdefaults()
        rcParams['font.family'] = 'Bitstream Vera Sans'
        rcParams['text.hinting'] = False
        try:
            rcParams['text.hinting_factor'] = 8
        except KeyError:
            warnings.warn("could not set rcParams['text.hinting_factor']")
        return self
コード例 #11
0
ファイル: vna.py プロジェクト: pavel-demin/red-pitaya-notes
 def plot_curves(self, freq, data1, label1, limit1, data2, label2, limit2):
   matplotlib.rcdefaults()
   matplotlib.rcParams['axes.formatter.use_mathtext'] = True
   self.figure.clf()
   bottom = len(self.cursors) * 0.04 + 0.13
   self.figure.subplots_adjust(left = 0.16, bottom = bottom, right = 0.84, top = 0.96)
   axes1 = self.figure.add_subplot(111)
   axes1.cla()
   axes1.xaxis.grid()
   axes1.set_xlabel('kHz')
   axes1.set_ylabel(label1)
   xlim = self.xlim(freq)
   axes1.set_xlim(xlim)
   if limit1 is not None: axes1.set_ylim(limit1)
   self.curve1, = axes1.plot(freq, data1, color = 'blue', label = label1)
   self.add_cursors(axes1)
   if data2 is None:
     self.canvas.draw()
     return
   axes1.tick_params('y', color = 'blue', labelcolor = 'blue')
   axes1.yaxis.label.set_color('blue')
   axes2 = axes1.twinx()
   axes2.spines['left'].set_color('blue')
   axes2.spines['right'].set_color('red')
   axes2.set_ylabel(label2)
   axes2.set_xlim(xlim)
   if limit2 is not None: axes2.set_ylim(limit2)
   axes2.tick_params('y', color = 'red', labelcolor = 'red')
   axes2.yaxis.label.set_color('red')
   self.curve2, = axes2.plot(freq, data2, color = 'red', label = label2)
   self.canvas.draw()
コード例 #12
0
ファイル: _mpl_backend.py プロジェクト: glue-viz/glue
def set_mpl_backend():

    from matplotlib import rcParams, rcdefaults

    # Standardize mpl setup
    rcdefaults()

    # Set default backend to Agg. The Qt and Jupyter glue applications don't
    # use the default backend, so this is just to make sure that importing
    # matplotlib doesn't cause errors related to the MacOSX or Qt backend.
    rcParams['backend'] = 'Agg'

    # Disable key bindings in matplotlib
    for setting in list(rcParams.keys()):
        if setting.startswith('keymap'):
            rcParams[setting] = ''

    # Set the MPLBACKEND variable explicitly, because ipykernel uses the lack of
    # MPLBACKEND variable to indicate that it should use its own backend, and
    # this in turn causes some rcParams to be changed, causing test failures
    # etc.
    os.environ['MPLBACKEND'] = 'Agg'

    # Explicitly switch backend
    from matplotlib.pyplot import switch_backend
    switch_backend('agg')
コード例 #13
0
ファイル: core.py プロジェクト: dopplershift/matplotlib
def context(style, after_reset=False):
    """Context manager for using style settings temporarily.

    Parameters
    ----------
    style : str, dict, or list
        A style specification. Valid options are:

        +------+-------------------------------------------------------------+
        | str  | The name of a style or a path/URL to a style file. For a    |
        |      | list of available style names, see `style.available`.       |
        +------+-------------------------------------------------------------+
        | dict | Dictionary with valid key/value pairs for                   |
        |      | `matplotlib.rcParams`.                                      |
        +------+-------------------------------------------------------------+
        | list | A list of style specifiers (str or dict) applied from first |
        |      | to last in the list.                                        |
        +------+-------------------------------------------------------------+

    after_reset : bool
        If True, apply style after resetting settings to their defaults;
        otherwise, apply style on top of the current settings.
    """
    with mpl.rc_context():
        if after_reset:
            mpl.rcdefaults()
        use(style)
        yield
コード例 #14
0
ファイル: __init__.py プロジェクト: janschulz/ggplot
def _setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    import locale
    import warnings
    from matplotlib.backends import backend_agg, backend_pdf, backend_svg

    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")

    mpl.use('Agg', warn=False)  # use Agg backend for these tests
    if mpl.get_backend().lower() != "agg":
        raise Exception(("Using a wrong matplotlib backend ({0}), which will not produce proper "
                        "images").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

    # Clear the font caches.  Otherwise, the hinting mode can travel
    # from one test to another.
    backend_agg.RendererAgg._fontd.clear()
    backend_pdf.RendererPdf.truetype_font_cache.clear()
    backend_svg.RendererSVG.fontd.clear()
コード例 #15
0
def wind_dir_pressure(year=2013):
    from statsmodels.nonparametric.kernel_density import KDEMultivariate as KDE
    import robust as rb

    min2 = 0
    sigfac = 3
    sigsamp = 5

    d = get_data(year=year)
    wdir = d["winddir_deg"]
    
    wdir_rand = wdir + np.random.normal(0,12,len(wdir))
    bad = np.isnan(wdir_rand)
    wdir_rand[bad] = np.random.uniform(0,360,np.sum(bad))
    
    press = d["pressure"]
    
    dist1 = wdir_rand
    dist2 = press
    
    med1 = np.median(dist1)
    sig1 = rb.std(dist1)
    datamin1 = np.min(dist1)
    datamax1 = np.max(dist1)
    min1 = 0.0
    max1 = 360.0


    med2 = np.median(dist2)
    sig2 = rb.std(dist2)
    datamin2 = np.min(dist2)
    datamax2 = np.max(dist2)
    min2 = np.min(dist2)
    max2 = np.max(dist2)
    
    X, Y = np.mgrid[min1:max1:100j, min2:max2:100j]
    positions = np.vstack([X.ravel(), Y.ravel()])
    values = np.vstack([dist1, dist2])
    
    kernel = KDE(values,var_type='cc',bw=[sig1/sigsamp,sig2/sigsamp])
    Z = np.reshape(kernel.pdf(positions).T, X.shape)
    
    aspect = (max1-min1)/(max2-min2) * 8.5/11.0

    plot_params()
    plt.ion()
    plt.figure(5,figsize=(11,8.5))
    plt.clf()
    ax = plt.subplot(111)
    ax.imshow(np.rot90(Z), cmap=plt.cm.CMRmap_r,aspect=aspect, \
              extent=[min1, max1, min2, max2],origin='upper')
    ax.yaxis.labelpad = 12
    ax.set_ylabel('Atmospheric Pressure (in-Hg)',fontsize=fs)
    ax.set_xlabel('Wind Direction (degrees)',fontsize=fs)
    plt.title('Wind Direction and Pressure at Thacher Observatory in '+str(year),fontsize=fs)
    
    plt.savefig('Wind_Direction_Pressure_'+str(year)+'.png',dpi=300)
    mpl.rcdefaults()

    return
コード例 #16
0
ファイル: __init__.py プロジェクト: Patrick-Reed/matplotlib
def setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    import locale
    import warnings

    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")

    use('Agg', warn=False) # use Agg backend for these tests

    # These settings *must* be hardcoded for running the comparison
    # tests and are not necessarily the default values as specified in
    # rcsetup.py
    rcdefaults()  # Start with all defaults
    rcParams['font.family'] = 'Bitstream Vera Sans'
    rcParams['text.hinting'] = False
    rcParams['text.hinting_factor'] = 8
コード例 #17
0
ファイル: __init__.py プロジェクト: aragilar/matplotlib
def setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    import locale
    import warnings
    from matplotlib.backends import backend_agg, backend_pdf, backend_svg

    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")

    use('Agg', warn=False)  # use Agg backend for these tests

    # These settings *must* be hardcoded for running the comparison
    # tests and are not necessarily the default values as specified in
    # rcsetup.py
    rcdefaults()  # Start with all defaults

    set_font_settings_for_testing()
コード例 #18
0
ファイル: test_misc.py プロジェクト: tsdlovell/pandas
    def setUp(self):
        TestPlotBase.setUp(self)
        import matplotlib as mpl
        mpl.rcdefaults()

        self.ts = tm.makeTimeSeries()
        self.ts.name = 'ts'
コード例 #19
0
ファイル: common.py プロジェクト: forking-repos/pandas
    def setup_method(self, method):

        import matplotlib as mpl
        from pandas.plotting._matplotlib import compat
        mpl.rcdefaults()

        self.mpl_ge_2_2_3 = compat._mpl_ge_2_2_3()
        self.mpl_ge_3_0_0 = compat._mpl_ge_3_0_0()
        self.mpl_ge_3_1_0 = compat._mpl_ge_3_1_0()

        self.bp_n_objects = 7
        self.polycollection_factor = 2
        self.default_figsize = (6.4, 4.8)
        self.default_tick_position = 'left'

        n = 100
        with tm.RNGContext(42):
            gender = np.random.choice(['Male', 'Female'], size=n)
            classroom = np.random.choice(['A', 'B', 'C'], size=n)

            self.hist_df = DataFrame({'gender': gender,
                                      'classroom': classroom,
                                      'height': random.normal(66, 4, size=n),
                                      'weight': random.normal(161, 32, size=n),
                                      'category': random.randint(4, size=n)})

        self.tdf = tm.makeTimeDataFrame()
        self.hexbin_df = DataFrame({"A": np.random.uniform(size=20),
                                    "B": np.random.uniform(size=20),
                                    "C": np.arange(20) + np.random.uniform(
                                        size=20)})
コード例 #20
0
ファイル: conftest.py プロジェクト: jwhendy/plotnine
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())
コード例 #21
0
ファイル: mystyle.py プロジェクト: PyCOMPLETE/PyPARIS
def mystyle(fontsz=10):
	
	font = {#'family' : 'normal',
			#'weight' : 'bold',
			'size'   : fontsz}
	print fontsz
	rcdefaults()
	rc('font', **font)
コード例 #22
0
ファイル: utils.py プロジェクト: alankarkotwal/astroplan
def _set_mpl_style_sheet(style_sheet):
    """
    Import matplotlib, set the style sheet to ``style_sheet`` using
    the most backward compatible import pattern.
    """
    import matplotlib
    matplotlib.rcdefaults()
    matplotlib.rcParams.update(style_sheet)
コード例 #23
0
def reset_matplotlib():
    """
    Reset matplotlib to a common default.
    """
    # Set all default values.
    mpl.rcdefaults()
    # Force agg backend.
    plt.switch_backend("agg")
コード例 #24
0
ファイル: vna.py プロジェクト: openchip/red-pitaya-notes
 def plot_smith(self):
   matplotlib.rcdefaults()
   self.figure.clf()
   self.figure.subplots_adjust(top = 0.90, right = 0.90)
   axes = self.figure.add_subplot(111, projection = 'smith', axes_radius = 0.55, axes_scale = 50.0)
   axes.cla()
   axes.plot(self.impedance())
   self.canvas.draw()
コード例 #25
0
def mystyle_2(fontsz=16, dist_tick_lab=10, figsize=(12,10)):
    rcdefaults()
    RcParams[u'axes.grid'] = True
    RcParams[u'axes.linewidth'] = 2.0
    RcParams[u'figure.facecolor'] = 'w'

    rc('font',**{'family':'sans-serif','sans-serif':['arial'], 'size':fontsz})
    rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=dist_tick_lab)
コード例 #26
0
ファイル: qa.py プロジェクト: sbrambati/toad
    def noiseAnalysis(self, source, maskNoise, maskCc, targetSnr, targetHist):
        """
        """
        dwiImage = nibabel.load(source)
        maskNoiseImage = nibabel.load(maskNoise)
        maskCcImage = nibabel.load(maskCc)

        dwiData = dwiImage.get_data()
        maskNoiseData = maskNoiseImage.get_data()
        maskCcData = maskCcImage.get_data()

        volumeNumber = dwiData.shape[3]

        if dwiData.shape[2] != maskNoiseData.shape[2]:
            zSliceShape = dwiData.shape[:2] + (1,)
            zMaskNoise = numpy.zeros(zSliceShape, dtype=maskNoiseData.dtype)
            zCc = numpy.zeros(zSliceShape, dtype=maskCcData.dtype)
            maskNoiseData = numpy.concatenate((maskNoiseData, zMaskNoise), axis=2)
            maskCcData = numpy.concatenate((maskCcData, zCc), axis=2)

        #Corpus Callossum masking
        dwiDataMaskCc = numpy.empty(dwiData.shape)
        maskCcData4d = numpy.tile(maskCcData,(volumeNumber,1,1,1))
        maskCcData4d = numpy.rollaxis(maskCcData4d, 0, start=4)
        dwiDataMaskCc = numpy.ma.masked_where(maskCcData4d == 0, dwiData)

        #Noise masking
        dwiDataMaskNoise = numpy.empty(dwiData.shape)
        maskNoise4d = numpy.tile(maskNoiseData,(volumeNumber,1,1,1))
        maskNoise4d = numpy.rollaxis(maskNoise4d, 0, start=4)
        dwiDataMaskNoise = numpy.ma.masked_where(maskNoise4d == 0, dwiData)

        #SNR
        volumeSize = numpy.prod(dwiData.shape[:3])
        mean_signal = numpy.reshape(dwiDataMaskCc, [volumeSize, volumeNumber])
        mean_signal = numpy.mean(mean_signal, axis=0)
        noise_std = numpy.reshape(dwiDataMaskNoise, [volumeSize, volumeNumber])
        noise_std = numpy.std(noise_std, axis=0)

        SNR = mean_signal / noise_std
        matplotlib.pyplot.plot(SNR)
        matplotlib.pyplot.xlabel('Volumes')
        matplotlib.pyplot.ylabel('SNR')
        matplotlib.pyplot.savefig(targetSnr)
        matplotlib.pyplot.close()
        matplotlib.rcdefaults()

        #Hist plot
        noiseHistData = dwiDataMaskNoise[:,:,:,1:]
        noiseHistData = numpy.reshape(noiseHistData, numpy.prod(noiseHistData.shape))
        num_bins = 40
        #xlim = numpy.percentile(noiseHistData, 98)
        matplotlib.pyplot.hist(noiseHistData, num_bins, histtype='stepfilled', facecolor='g', range=[0, 150])
        matplotlib.pyplot.xlabel('Intensity')
        matplotlib.pyplot.ylabel('Voxels number')
        matplotlib.pyplot.savefig(targetHist)
        matplotlib.pyplot.close()
        matplotlib.rcdefaults()
コード例 #27
0
ファイル: gui_util.py プロジェクト: megies/pyrocko
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        
        bgrgb = self.palette().color(QPalette.Window).getRgb()[:3]
        fgcolor = pyrocko.plot.tango_colors['aluminium5'] 
        dpi = 0.5*(self.logicalDpiX() + self.logicalDpiY())
    
        font = QFont()
        font.setBold(True)
        fontsize = font.pointSize()
        
        import matplotlib
        matplotlib.rcdefaults()
        matplotlib.rc('xtick', direction='out', labelsize=fontsize)
        matplotlib.rc('ytick', direction='out', labelsize=fontsize)
        matplotlib.rc('xtick.major', size=8)
        matplotlib.rc('xtick.minor', size=4)
        matplotlib.rc('ytick.major', size=8)
        matplotlib.rc('ytick.minor', size=4)
        #matplotlib.rc('figure', facecolor=tohex(bgrgb), edgecolor=tohex(fgcolor))
        matplotlib.rc('figure', facecolor='white', edgecolor=tohex(fgcolor))
        matplotlib.rc('font', family='sans-serif', weight='bold', size=fontsize, **{ 'sans-serif': [font.family()] })
        matplotlib.rc('text', color=tohex(fgcolor))
        matplotlib.rc('xtick', color=tohex(fgcolor))
        matplotlib.rc('ytick', color=tohex(fgcolor))
        matplotlib.rc('figure.subplot', bottom=0.15)

        matplotlib.rc('axes', linewidth=0.5, unicode_minus=False)
        matplotlib.rc('axes', facecolor='white', edgecolor=tohex(fgcolor), labelcolor=tohex(fgcolor))

        try:
            matplotlib.rc('axes', color_cycle=[ to01(x) for x in pyrocko.plot.graph_colors ])
        except KeyError:
            pass

        try:
            matplotlib.rc('axes', labelsize=fontsize)
        except KeyError:
            pass

        try:
            matplotlib.rc('axes', labelweight='bold')
        except KeyError:
            pass

        from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
        from matplotlib.figure import Figure
        
        layout = QGridLayout()
        layout.setContentsMargins(0,0,0,0)
        layout.setSpacing(0)
        
        self.setLayout(layout)
        self.figure = Figure(dpi=dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)
        layout.addWidget(self.canvas, 0,0)
コード例 #28
0
ファイル: cake_plot.py プロジェクト: kshramt/pyrocko
def mpl_init():
    import matplotlib
    matplotlib.rcdefaults()
    matplotlib.rc('axes', linewidth=1.5)
    matplotlib.rc('xtick', direction='out')
    matplotlib.rc('ytick', direction='out')
    matplotlib.rc('xtick.major', size=5)
    matplotlib.rc('ytick.major', size=5)
    matplotlib.rc('figure', facecolor='white')
コード例 #29
0
ファイル: __init__.py プロジェクト: ddale/matplotlib
def setup():
    use('Agg', warn=False) # use Agg backend for these tests

    # These settings *must* be hardcoded for running the comparison
    # tests and are not necessarily the default values as specified in
    # rcsetup.py
    rcdefaults() # Start with all defaults
    rcParams['font.family'] = 'Bitstream Vera Sans'
    rcParams['text.hinting'] = False
コード例 #30
0
 def backend_switcher(*args, **kwargs):
     try:
         prev_backend = mpl.get_backend()
         mpl.rcdefaults()
         plt.switch_backend(backend)
         result = func(*args, **kwargs)
     finally:
         plt.switch_backend(prev_backend)
     return result
コード例 #31
0
"""
Created on Thu May 26 09:51:41 2016

@author: wal
"""
import pdb
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.font_manager import FontProperties
import matplotlib.patheffects as path_effects

plt.close()
mpl.rcdefaults()
mpl.rcParams['figure.figsize'] = 14, 16
plt.style.use('ggplot')
font = {'family': 'normal', 'weight': 'bold', 'size': 14}

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

tc_dict = {
    'Avril LaGreen': ['#12D300', '#FF0000'],
    'SWAg': ['#EFEFEF', '#FF0000'],
    'Mediokra': ['#38761D', '#FFFF00'],
    'MAGA': ['#999999', '#FF9900'],
    'Cheerwine?': ['#CC0000', '#FF9900'],
    'Blue Ridge': ['#0000FF', '#FF9900'],
    'ThunderPants': ['#000000', '#FF0000'],
    'Victorious Secret': ['#FF00FF', '#000000'],
コード例 #32
0
def clear_state(plot_rcparams):
    plt.close('all')
    matplotlib.rcdefaults()
    matplotlib.rcParams.update(plot_rcparams)
コード例 #33
0
import time
from scipy.ndimage.filters import generic_filter as gf
from matplotlib.ticker import MultipleLocator
import matplotlib.gridspec as gridspec
import scipy.integrate as integrate

from astropy import units as u
from astropy import cosmology
import matplotlib.ticker as mtick
import PlotScripts
import ReadScripts
import AllVars

colors = ['r', 'b', 'g', 'c', 'm', 'k']

matplotlib.rcdefaults()
plt.rc('axes',
       color_cycle=['k', 'b', 'r', 'g', 'm', 'c', 'y', '0.5'],
       labelsize='x-large')
plt.rc('lines', linewidth='2.0')
# plt.rc('font', variant='monospace')
plt.rc('legend', numpoints=1, fontsize='x-large')
plt.rc('text', usetex=True)

label_size = 20  # 12 for paper.
extra_size = 2
legend_size = 16  # 20 for paper.
plt.rc('xtick', labelsize=label_size)
plt.rc('ytick', labelsize=label_size)