Python matplotlib.cm.viridis() Examples

The following are code examples for showing how to use matplotlib.cm.viridis(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: opt_trade   Author: ejpjapan   File: implied_to_realized.py    MIT License 6 votes vote down vote up
def plot_vol_forecast(self, num_days=10):
        expected_volatility = self.expected_vol
        fig, ax = plt.subplots(figsize=(12, 5), dpi=80, facecolor='w', edgecolor='k')

        for i in range(-1, -(num_days + 1), -1):
            if i == -1:
                expected_volatility.iloc[:, -1].plot(color='r')
            else:
                c = cm.viridis(-i / num_days, 1)
                expected_volatility.iloc[:, i].plot(color=c)

        plt.autoscale(enable=True, axis='x', tight=True)
        legend_labels = expected_volatility.iloc[:, -num_days:].columns.strftime('%d-%b')
        _ = plt.legend(legend_labels[::-1])
        _ = plt.title('HAR Volatity Forecast')
        _ = ax.set_ylabel('Annualized Vol %')
        return ax 
Example 2
Project: gaia_tools   Author: jobovy   File: tgasSelect.py    MIT License 6 votes vote down vote up
def plot_mean_quantity_tgas(self,tag,func=None,**kwargs):
        """
        NAME:
           plot_mean_quantity_tgas
        PURPOSE:
           Plot the mean of a quantity in the TGAS catalog on the sky
        INPUT:
           tag - tag in the TGAS data to plot
           func= if set, a function to apply to the quantity
           +healpy.mollview plotting kwargs
        OUTPUT:
           plot to output device
        HISTORY:
           2017-01-17 - Written - Bovy (UofT/CCA)
        """
        mq= self._compute_mean_quantity_tgas(tag,func=func)
        cmap= cm.viridis
        cmap.set_under('w')
        kwargs['unit']= kwargs.get('unit',tag)
        kwargs['title']= kwargs.get('title',"")
        healpy.mollview(mq,nest=True,cmap=cmap,**kwargs)
        return None 
Example 3
Project: fooof   Author: fooof-tools   File: plot_mne_example.py    Apache License 2.0 6 votes vote down vote up
def plot_topo_colorbar(vmin, vmax, label):
    """Helper function to create colorbars for the topography plots."""

    fig = plt.figure(figsize=(2, 3))
    ax1 = fig.add_axes([0.9, 0.25, 0.15, 0.9])

    cmap = cm.viridis
    norm = colors.Normalize(vmin=vmin, vmax=vmax)

    cb1 = colorbar.ColorbarBase(plt.gca(), cmap=cmap,
                                norm=norm, orientation='vertical')

###################################################################################################
#
# In this example, we will be plotting the alpha center frequency and oscillatory exponent.

###################################################################################################

# Settings to grab the alpha center frequency 
Example 4
Project: safe-exploration   Author: befelix   File: create_exploration_plots_paper.py    MIT License 6 votes vote down vote up
def create_color_bar(n_iterations,bar_label = "Iteration"):
    fig = plt.figure(figsize=(2, 4.5))
    ax1 = fig.add_axes([0.05, 0.05, 0.2, 0.9])

    # Set the colormap and norm to correspond to the data for which
    # the colorbar will be used.
    cmap = mpl.cm.viridis
    norm = mpl.colors.Normalize(vmin=1, vmax=n_iterations)

    # ColorbarBase derives from ScalarMappable and puts a colorbar
    # in a specified axes, so it has everything needed for a
    # standalone colorbar.  There are many more kwargs, but the
    # following gives a basic continuous colorbar with ticks
    # and labels.
    cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
	                norm=norm,
	                orientation='vertical')
    cb1.set_label(bar_label)

    return fig, ax1 
Example 5
Project: safe-exploration   Author: befelix   File: create_dynamic_expl_plots.py    MIT License 6 votes vote down vote up
def plot_sample_set(x_train,z_all,env):
    """ plot the sample set"""
    
    s_train = x_train[:,:env.n_s]
    n_train = np.shape(s_train)[0]
    
    s_expl = z_all[:,:env.n_s]
    n_it = np.shape(s_expl)[0]
    fig, ax = env.plot_safety_bounds(color = "r")
    
    c_spectrum = viridis(np.arange(n_it))
    # plot initial dataset    
    for i in range(n_train):
        ax = env.plot_state(ax,s_train[i,:env.n_s],color = c_spectrum[0])
    
    # plot the data gatehred
    for i in range(n_it):
        ax = env.plot_state(ax,s_expl[i,:env.n_s],color = c_spectrum[i])
        
    return fig, ax 
Example 6
Project: safe-exploration   Author: befelix   File: create_static_expl_plots.py    MIT License 6 votes vote down vote up
def plot_sample_set(x_train,z_all,env):
    """ plot the sample set"""
    
    s_train = x_train[:,:env.n_s]
    n_train = np.shape(s_train)[0]
    
    s_expl = z_all[:,:env.n_s]
    n_it = np.shape(s_expl)[0]
    fig, ax = env.plot_safety_bounds(color = "r")
    
    c_spectrum = viridis(np.arange(n_it))
    # plot initial dataset    
    for i in range(n_train):
        ax = env.plot_state(ax,s_train[i,:env.n_s],color = c_spectrum[0])
    
    # plot the data gatehred
    for i in range(n_it)        :
        ax = env.plot_state(ax,s_expl[i,:env.n_s],color = c_spectrum[i])
        
    return fig, ax 
Example 7
Project: form2fit   Author: kevinzakka   File: main.py    MIT License 6 votes vote down vote up
def _get_next_data(self):
        """Grabs a fresh pair of source and target data points.
        """
        self._pair_idx += 1
        self.imgs, labels, center = next(self._dloader)
        self.center = center[0]
        label = labels[0]
        self.xs, self.xt = self.imgs[:, :self._num_channels, :, :], self.imgs[:, self._num_channels:, :, :]
        if self._num_channels == 4:
            self._xs_np = ml.tensor2ndarray(self.xs[:, :3], [self._color_mean * 3, self._color_std * 3])
            self._xt_np = ml.tensor2ndarray(self.xt[:, :3], [self._color_mean * 3, self._color_std * 3])
        else:
            self._xs_np = ml.tensor2ndarray(self.xs[:, :1], [self._color_mean, self._color_std], False)
            self._xt_np = ml.tensor2ndarray(self.xt[:, :1], [self._color_mean, self._color_std], False)
            self._xs_np = np.uint8(cm.viridis(self._xs_np) * 255)[..., :3]
            self._xt_np = np.uint8(cm.viridis(self._xt_np) * 255)[..., :3]
        source_idxs = label[:, 0:2]
        target_idxs = label[:, 2:4]
        rot_idx = label[:, 4]
        is_match = label[:, 5]
        self.best_rot_idx = rot_idx[0].item()
        mask = (is_match == 1) & (rot_idx == self.best_rot_idx)
        self.source_pixel_idxs = source_idxs[mask].numpy()
        self.target_pixel_idxs = target_idxs[mask].numpy() 
Example 8
Project: mrf-reconstruction-midl2019   Author: fabianbalsiger   File: plt_qualitative.py    MIT License 6 votes vote down vote up
def plot(self, subject: str, map_name: str, prediction: np.ndarray, ground_truth: np.ndarray, mask_fg: np.ndarray):
        mask = np.squeeze(mask_fg)  # due to dataset convention
        map_name_short = map_name.replace('map', '')

        # calculate error
        error = prediction - ground_truth
        error[mask == 0] = 0  # the min intensity of the ground truth might not be 0,
        # i.e. background would have an error

        path = os.path.join(self.path, '{}_{}_{}_{}.{}'.format(subject,
                                                               map_name_short,
                                                               '{}',
                                                               self.slice_no,
                                                               self.plot_format))

        plot_2d_image_colorbar(path.format('PRED'), prediction[self.slice_no, ...],
                               min_value=ground_truth.min(), max_value=ground_truth.max(),
                               cmap=get_colormap(map_name))

        plot_2d_image_colorbar(path.format('ERR'), error[self.slice_no, ...], cmap=cm.get_cmap('viridis')) 
Example 9
Project: autoregressive-energy-machines   Author: conormdurkan   File: plane.py    MIT License 6 votes vote down vote up
def test():
    n = int(1e6)
    dataset = GaussianGridDataset(n)
    samples = dataset.data

    fig, ax = plt.subplots(1, 1, figsize=(5, 5))

    # ax.hist2d(samples[:, 0], samples[:, 1],
    #               range=[[0, 1], [0, 1]], bins=512, cmap=cm.viridis)
    ax.hist2d(samples[:, 0], samples[:, 1], range=[[-4, 4], [-4, 4]], bins=512,
              cmap=cm.viridis)

    ax.set_xticks([])
    ax.set_yticks([])

    plt.show()
    # path = os.path.join(utils.get_output_root(), 'plane-test.png')
    # plt.savefig(path, rasterized=True) 
Example 10
Project: pyplis   Author: jgliss   File: image.py    GNU General Public License v3.0 5 votes vote down vote up
def get_cmap(self, vmin=None, vmax=None, **kwargs):
        """Determine and return default cmap for current image."""
        if self.is_tau or self.is_aa:
            return cmaps.viridis
# =============================================================================
#             if vmin is None:
#                 vmin = self.min()
#             if vmax is None:
#                 vmax = self.max()
#             return shifted_color_map(vmin, vmax, cmaps.RdBu)
# =============================================================================
        return cmaps.gray 
Example 11
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 5 votes vote down vote up
def viridis():
    '''
    set the default colormap to viridis and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='viridis')
    im = gci()

    if im is not None:
        im.set_cmap(cm.viridis)


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 12
Project: mlAlgorithms   Author: robotenique   File: osregression.py    The Unlicense 5 votes vote down vote up
def main():
    data = np.loadtxt('osdata.txt', delimiter=',')
    print(data)
    X = data[:, :3]
    X = np.column_stack((X, X[:, 2]**2))
    y = data[:, 3]
    m = y.T.size
    regr = linear_model.LinearRegression(fit_intercept=False, normalize=True)
    regr.fit(X, y)

    print('Theta found: ')
    print('%s %s %s %s\n' % (regr.coef_[0], regr.coef_[1],regr.coef_[2], regr.coef_[3]))
    #theta learned = 0.195797846404 1.14970377455 0.0370065601353
    print("Predição P(t0, dt, Punctuality, Punctuality²):")
    predict([0, 3, 0.5, 0.5**2],regr)
    predict([10, 30, 4, 4**2],regr)
    predict([20, 20, 20, 20**2],regr)
    predict([20, 3, 10, 10**2],regr)
    # Surface plot
    fig = plt.figure(figsize=(10, 10))
    ax = fig.gca(projection='3d')
    plotPriority(regr, 400, -100, fig, ax, cm.magma)
    plotPriority(regr, 400, 50, fig, ax, cm.plasma)
    plotPriority(regr, 400, 200, fig, ax, cm.viridis)
    plotQuantumF()
    plt.show() 
Example 13
Project: audio_conditioned_unet   Author: CPJKU   File: video_utils.py    MIT License 5 votes vote down vote up
def prepare_spec_for_render(spec, score, scale_factor=5):
    spec_excerpt = cv2.resize(np.flipud(spec), (spec.shape[1] * scale_factor, spec.shape[0] * scale_factor))

    perf_img = np.pad(cm.viridis(spec_excerpt)[:, :, :3],
                      ((score.shape[0] // 2 - spec_excerpt.shape[0] // 2 + 1,
                        score.shape[0] // 2 - spec_excerpt.shape[0] // 2),
                       (20, 20), (0, 0)), mode="constant")

    return perf_img 
Example 14
Project: gaia_tools   Author: jobovy   File: tgasSelect.py    MIT License 5 votes vote down vote up
def plot_2mass(self,jmin=None,jmax=None,
                   jkmin=None,jkmax=None,
                   cut=False,
                   **kwargs):
        """
        NAME:
           plot_2mass
        PURPOSE:
           Plot star counts in 2MASS
        INPUT:
           If the following are not set, fullsky will be plotted:
              jmin, jmax= minimum and maximum Jt
              jkmin, jkmax= minimum and maximum J-Ks
           cut= (False) if True, cut to the 'good' sky
           +healpy.mollview plotting kwargs
        OUTPUT:
           plot to output device
        HISTORY:
           2017-01-17 - Written - Bovy (UofT/CCA)
        """
        # Select stars
        if jmin is None or jmax is None \
                or jkmin is None or jkmax is None:
            pt= _2mc_skyonly[1]
        else:
            pindx= (_2mc[0] > jmin)*(_2mc[0] < jmax)\
                *(_2mc[1] > jkmin)*(_2mc[1] < jkmax)
            pt, e= numpy.histogram(_2mc[2][pindx],
                                   range=[-0.5,_BASE_NPIX-0.5],
                                   bins=_BASE_NPIX)
        pt= numpy.log10(pt)
        if cut: pt[self._exclude_mask_skyonly]= healpy.UNSEEN
        cmap= cm.viridis
        cmap.set_under('w')
        kwargs['unit']= r'$\log_{10}\mathrm{number\ counts}$'
        kwargs['title']= kwargs.get('title',"")
        healpy.mollview(pt,nest=True,cmap=cmap,**kwargs)
        return None 
Example 15
Project: gaia_tools   Author: jobovy   File: tgasSelect.py    MIT License 5 votes vote down vote up
def plot_tgas(self,jmin=None,jmax=None,
                  jkmin=None,jkmax=None,
                  cut=False,
                  **kwargs):
        """
        NAME:
           plot_tgas
        PURPOSE:
           Plot star counts in TGAS
        INPUT:
           If the following are not set, fullsky will be plotted:
              jmin, jmax= minimum and maximum Jt
              jkmin, jkmax= minimum and maximum J-Ks
           cut= (False) if True, cut to the 'good' sky
           +healpy.mollview plotting kwargs
        OUTPUT:
           plot to output device
        HISTORY:
           2017-01-17 - Written - Bovy (UofT/CCA)
        """
        # Select stars
        if jmin is None or jmax is None \
                or jkmin is None or jkmax is None:
            pt= self._nstar_tgas_skyonly
        else:
            pindx= (self._full_jt > jmin)*(self._full_jt < jmax)\
                *(self._full_jk > jkmin)*(self._full_jk < jkmax)
            pt, e= numpy.histogram((self._full_tgas['source_id']/2**(35.\
                      +2*(12.-numpy.log2(_BASE_NSIDE)))).astype('int')[pindx],
                                   range=[-0.5,_BASE_NPIX-0.5],
                                   bins=_BASE_NPIX)
        pt= numpy.log10(pt)
        if cut: pt[self._exclude_mask_skyonly]= healpy.UNSEEN
        cmap= cm.viridis
        cmap.set_under('w')
        kwargs['unit']= r'$\log_{10}\mathrm{number\ counts}$'
        kwargs['title']= kwargs.get('title',"")
        healpy.mollview(pt,nest=True,cmap=cmap,**kwargs)
        return None 
Example 16
Project: blob-explorer   Author: jni   File: picker.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def bokeh_plot(df):
    tooltip = """
        <div>
            <div>
                <img
                src="@image_files" height="60" alt="image"
                style="float: left; margin: 0px 15px 15px 0px; image-rendering: pixelated;"
                border="2"
                ></img>
            </div>
            <div>
                <span style="font-size: 17px;">@source_filenames</span>
            </div>
        </div>
              """
    filenames = b64_image_files(df['images'])
    df['image_files'] = filenames
    colors_raw = cm.viridis((df['time'] - df['time'].min()) /
                            (df['time'].max() - df['time'].min()), bytes=True)
    colors_str = ['#%02x%02x%02x' % tuple(c[:3]) for c in colors_raw]
    df['color'] = colors_str
    source = ColumnDataSource(df)
    bplot.output_file('plot.html')
    hover0 = HoverTool(tooltips=tooltip)
    hover1 = HoverTool(tooltips=tooltip)
    tools0 = [t() for t in TOOLS] + [hover0]
    tools1 = [t() for t in TOOLS] + [hover1]
    pca = bplot.figure(tools=tools0)
    pca.circle('PC1', 'PC2', color='color', source=source)
    tsne = bplot.figure(tools=tools1)
    tsne.circle('tSNE-0', 'tSNE-1', color='color', source=source)
    p = bplot.gridplot([[pca, tsne]])
    bplot.show(p) 
Example 17
Project: RNAsketch   Author: ViennaRNA   File: design-energyshift.py    GNU General Public License v3.0 5 votes vote down vote up
def plotRegression(simple, turner, slope, intercept, r_value):
    import matplotlib.pyplot as plt
    import matplotlib.pylab as pylab
    import matplotlib.cm as cm
    
    # make histogram plot
    params = {'legend.fontsize': 'x-large',
             'figure.figsize': (7, 5),
             'axes.labelsize': 'x-large',
             'axes.titlesize':'x-large',
             'xtick.labelsize':'x-large',
             'ytick.labelsize':'x-large'}
    pylab.rcParams.update(params)
    #fig, axes = plt.subplots(3, 1, sharex=False, sharey=False)
    fig = plt.figure()
    plt.xlabel("Energy of Structure in Simple Model [kcal/mol]")
    plt.ylabel("Energy of Structure in Turner Model [kcal/mol]")
    fig.legend().set_visible(False)
    color_i = 0.0

    for t in slope.keys():
        plt.plot(simple[:,t], turner[:,t], '.', color=cm.viridis(color_i), label=str(t), alpha=0.5)
        plt.plot(simple[:,t], slope[t] * simple[:,t]+ intercept[t], '-', color=cm.viridis(color_i))
        fig.text(0.16, 0.81-color_i/7, "$R^{2}$ = "+"{0:.3f}".format(r_value[t]), color=cm.viridis(color_i))
        # increment color
        color_i += 0.3
    #plt.legend(loc='upper left')
    fig.savefig('regression.svg', dpi=300) 
Example 18
Project: safe-exploration   Author: befelix   File: create_exploration_plots_paper.py    MIT License 5 votes vote down vote up
def plot_sample_set(z_all,env,y_label = False, x_train = None):
    """ plot the sample set"""
    
    
    
    s_expl = z_all[:,:env.n_s]
    n_it = np.shape(s_expl)[0]
    fig, ax = env.plot_safety_bounds(color = "r")
    
    c_spectrum = viridis(np.arange(n_it))
    # plot initial dataset    
    if not x_train is None:
	s_train = x_train[:,:env.n_s]
        n_train = np.shape(s_train)[0]
        for i in range(n_train):
            ax = env.plot_state(ax,s_train[i,:env.n_s],color = c_spectrum[0])
    
    # plot the data gatehred
    for i in range(n_it):
        ax = env.plot_state(ax,s_expl[i,:env.n_s],color = c_spectrum[i])
        
    ax.set_xlabel("Angular velocity $\dot{\\theta}$")
    print(y_label)
    if y_label:
	print("??")
	ax.set_ylabel("Angle $\\theta$")
    fig.set_size_inches(3.6,4.5)
    return fig, ax 
Example 19
Project: form2fit   Author: kevinzakka   File: main.py    MIT License 5 votes vote down vote up
def _draw_rotations(self, init=False, heatmap=True):
        def _hist_eq(img):
            from skimage import exposure

            img_cdf, bin_centers = exposure.cumulative_distribution(img)
            return np.interp(img, bin_centers, img_cdf)

        for col in range(5):
            for row in range(4):
                offset = col * 4 + row
                if init:
                    img = self._zeros.copy()
                else:
                    if heatmap:
                        img = self.heatmaps[offset].copy()
                        img = img / img.max()
                        img = _hist_eq(img)
                        img = np.uint8(cm.viridis(img) * 255)[..., :3]
                        img = img.copy()
                    else:
                        img = misc.rotate_img(self._xs_np, -(360 / 20) * offset, center=(self.center[1], self.center[0]))
                        img = img.copy()
                    if offset == self._uv[-1]:
                        img[
                            self._uv[0] - 1 : self._uv[0] + 1,
                            self._uv[1] - 1 : self._uv[1] + 1,
                        ] = [255, 0, 0]
                        self._add_border_clr(img, [255, 0, 0])
                    if offset == self.best_rot_idx:
                        self._add_border_clr(img, [0, 255, 0])
                self._img = QImage(
                    img.data, self._w, self._h, self._c * self._w, QImage.Format_RGB888
                )
                pixmap = QPixmap.fromImage(self._img)
                self._grid_widgets[offset].setPixmap(pixmap)
                self._grid_widgets[offset].setScaledContents(True) 
Example 20
Project: PHi-C   Author: soyashinkai   File: plot_cost_decay.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    decay1000kb = np.loadtxt(
        "Bonev_ES_observed_KR_chr06_50-100Mb_res1000kb/optimized_data/decay_cost.txt")
    decay500kb = np.loadtxt(
        "Bonev_ES_observed_KR_chr06_50-100Mb_res500kb/optimized_data/decay_cost.txt")
    decay250kb = np.loadtxt(
        "Bonev_ES_observed_KR_chr06_50-100Mb_res250kb/optimized_data/decay_cost.txt")
    decay100kb = np.loadtxt(
        "Bonev_ES_observed_KR_chr06_50-100Mb_res100kb/optimized_data/decay_cost.txt")
    # ----------------------------------------------------------------------------------------------
    plt.rcParams["font.family"] = "Arial"
    plt.rcParams["font.size"] = 24
    # ----------------------------------------------------------------------------------------------
    FILE_FIG = "cost_decay.png"
    plt.figure(figsize=(8, 6))
    plt.xlim(0, 7e5)
    plt.ylim(0, 220)
    plt.xlabel(r"$\mathrm{\mathbf{Iteration}}$")
    plt.ylabel(r"$\mathrm{\mathbf{Cost}}$")

    plt.plot(decay100kb[:, 0], decay100kb[:, 1], linewidth=3,
             label="500x500 (bin size: 100 kb, $r$ = 0.972)", color=cm.viridis(0.0))
    plt.plot(decay250kb[:, 0], decay250kb[:, 1], linewidth=3,
             label="200x200 (bin size: 250 kb, $r$ = 0.984)", color=cm.viridis(0.333))
    plt.plot(decay500kb[:, 0], decay500kb[:, 1], linewidth=3,
             label="100x100 (bin size: 500 kb, $r$ = 0.990)", color=cm.viridis(0.666))
    plt.plot(decay1000kb[:, 0], decay1000kb[:, 1], linewidth=3,
             label="50x50 (bin size: 1 Mb, $r$ = 0.995)", color=cm.viridis(1.0))

    plt.legend(fontsize=20)
    plt.tight_layout()
    plt.savefig(FILE_FIG)
    plt.close()
# -------------------------------------------------------------------------------------------------- 
Example 21
Project: mrf-reconstruction-midl2019   Author: fabianbalsiger   File: plt_qualitative.py    MIT License 5 votes vote down vote up
def get_colormap(map_: typing.Union[str, data.FileTypes]):
    if isinstance(map_, data.FileTypes):
        map_ = map_.name

    if map_ == data.FileTypes.T1H2Omap.name:
        return cm.get_cmap('viridis')  # Benjamin uses jet
    elif map_ == data.FileTypes.FFmap.name:
        return cm.get_cmap('gray')
    elif map_ == data.FileTypes.B1map.name:
        return cm.get_cmap('plasma')  # Benjamin uses jet
    else:
        raise ValueError('Map {} not supported'.format(map_.replace('map', ''))) 
Example 22
Project: evolutionary-optimization   Author: strongio   File: ArtificialLandscapeOptimization.py    MIT License 5 votes vote down vote up
def plot_functions(func='rastrigin'):
    def func_group(*X, **kwargs):
        func = kwargs.get('func', None)
        return func(X)
    assert func in FUNCS.keys()
    X = np.linspace(-5, 5, 100)
    Y = np.linspace(-5, 5, 100)

    X, Y = np.meshgrid(X, Y)
    Z = func_group(X, Y, func=FUNCS[func])

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

    ax.plot_surface(
        X, Y, Z,
        rstride=1,
        cstride=1,
        cmap=cm.viridis,
        linewidth=0,
        antialiased=False
    )
    for i in range(6):
        angle = 15 + 360 / 6 * i
        ax.view_init(30, angle)
        plt.tight_layout()
        plt.savefig('./images/3d-{0}-{1}.png'.format(func, angle)) 
Example 23
Project: Blackjack-Tracker   Author: martinabeleda   File: pyplot.py    MIT License 5 votes vote down vote up
def viridis():
    '''
    set the default colormap to viridis and apply to current image if any.
    See help(colormaps) for more information
    '''
    rc('image', cmap='viridis')
    im = gci()

    if im is not None:
        im.set_cmap(cm.viridis)


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 24
Project: synthetic-image-morph   Author: gsnyder206   File: gfs_twod_histograms.py    GNU General Public License v2.0 5 votes vote down vote up
def make_twod_grid(axi,xparam,yparam,other_params,other_function,bins=20,tiles=(0.90,0.50),percentiles=False,numbers=[10,100],vmin=0.0,vmax=1.0,bad_offset=-1000.0,flipx=False,**bin_kwargs):


    xlim = axi.get_xlim()
    ylim = axi.get_ylim()

    if flipx is True:
        xlim_use = np.flipud(xlim)
    else:
        xlim_use = xlim
        
    value_twod, hist_twod, xMR, yMR, dx, dy = execute_twodim(xparam,yparam,xlim_use,ylim,other_params,other_function,bins=bins,vmin=vmin,**bin_kwargs) #passive_fractions_twodim(xparam,yparam,xlimits,ylimits,CONDITIONAL,sfr_all,mstar_all,bins=bins)

    
    themap = cm.viridis
    Zm = ma.masked_where(value_twod <= bad_offset , value_twod)
    
    
    cscale_function = pycolors.Normalize(vmin=vmin,vmax=vmax,clip=True)

    colorobj = axi.imshow(np.transpose((Zm)),vmin=vmin,vmax=vmax,origin='lower',aspect='auto',interpolation='nearest',extent=[xlim_use[0],xlim_use[1],ylim[0],ylim[1]],cmap=themap)
        
    if percentiles==True:
        levels = get_levels_from_percentiles(MR_hist*1.0,tiles)
        axi.contour(xMR[1:]-dx/2.0,yMR[1:]-dy/2.0,np.transpose(np.log10(MR_hist+0.001)),np.log10(levels),linewidths=1.0,colors=['silver','white'])
    else:
        axi.contour(xMR[1:]-dx/2.0,yMR[1:]-dy/2.0,np.transpose(np.log10(hist_twod+0.001)),(np.log10(numbers[0]),np.log10(numbers[1])),linewidths=0.5,colors=['silver','white'])




    return axi, colorobj 
Example 25
Project: karabo_data   Author: European-XFEL   File: geometry.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_data(self, modules_data):
        """Plot data from the detector using this geometry.

        Returns a matplotlib figure.

        Parameters
        ----------

        modules_data : ndarray
          Should have exactly 3 dimensions: channelno, pixel_y, pixel_x
          (lengths 16, 256, 256).
        """
        from matplotlib.cm import viridis
        from matplotlib.backends.backend_agg import FigureCanvasAgg
        from matplotlib.figure import Figure

        fig = Figure((10, 10))
        FigureCanvasAgg(fig)
        ax = fig.add_subplot(1, 1, 1)
        my_viridis = copy(viridis)
        # Use a dark grey for missing data
        my_viridis.set_bad('0.25', 1.0)

        res, centre = self.position_all_modules(modules_data)
        ax.imshow(res, cmap=my_viridis)

        cx, cy = centre
        ax.hlines(cy, cx - 20, cx + 20, colors='w', linewidths=1)
        ax.vlines(cx, cy - 20, cy + 20, colors='w', linewidths=1)
        return fig 
Example 26
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 4 votes vote down vote up
def PlotChiElevationMChi(BasinID):
    
    # load the channel data
    ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)

    if (BasinChannelData.count == 0):
        print("No Channel Data for Basin ID " + str(BasinID))

    # isolate basin data
    BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
    MinimumChi = BasinChannelData.chi.min()
    MaximumMChi = BasinChannelData.m_chi.max()
    
    # how many segments are we dealing with?    
    Segments = BasinChannelData.segment_number.unique()
    
    # setup the figure
    Fig = CreateFigure()
    
    #choose colormap
    ColourMap = cm.viridis
    
    # Get the data columns for plotting
    for i in range(0, len(Segments)):
        #get data arrays
        Chi = ChannelData.chi[ChannelData.segment_number == Segments[i]]
        Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
        SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
        MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
        
        #normalise chi by outlet chi
        Chi = Chi-MinimumChi
        #plot, colouring segments
        Colour = MChi/MaximumMChi
        plt.plot(Chi,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
        plt.plot(Chi, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
    
    # Finalise the figure
    plt.xlabel(r'$\chi$ (m)')
    plt.ylabel('Elevation (m)')
    plt.title('Basin ID ' + str(BasinID))
    plt.tight_layout()
    #add colourbar
    CAx = Fig.add_axes([0.15,0.8,0.4,0.05])
    m = cm.ScalarMappable(cmap=ColourMap)
    m.set_array(ChannelData.m_chi)
    plt.colorbar(m, cax=CAx,orientation='horizontal')
    plt.xlabel('$M_{\chi}$ m$^{0.64}$')
    #save output
    plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_ChiElevMChi.png", dpi=300)
    plt.close() 
Example 27
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 4 votes vote down vote up
def PlotLongProfileMChi(BasinID):
    
    # load the channel data
    ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)

    # isolate basin data
    BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
    
    if (BasinChannelData.count == 0):
        print("No Channel Data for Basin ID " + str(BasinID))
        
    MinimumDistance = BasinChannelData.flow_distance.min()
    MaximumMChi = BasinChannelData.m_chi.max()
    
    # how many segments are we dealing with?    
    Segments = BasinChannelData.segment_number.unique()
    
    # setup the figure
    Fig = CreateFigure()
    
    #choose colormap
    ColourMap = cm.viridis
        
    # Get the data columns for plotting
    for i in range(0, len(Segments)):
        #get data arrays
        Dist = ChannelData.flow_distance[ChannelData.segment_number == Segments[i]]
        Elevation = ChannelData.elevation[ChannelData.segment_number == Segments[i]]
        SegmentedElevation = ChannelData.segmented_elevation[ChannelData.segment_number == Segments[i]]
        MChi = ChannelData.m_chi[ChannelData.segment_number == Segments[i]].unique()[0]
        
        #normalise distance by outlet distance
        Dist = Dist-MinimumDistance
        #plot, colouring segments
        Colour = MChi/MaximumMChi
        plt.plot(Dist/1000,Elevation,'k--',dashes=(2,2), lw=0.5,zorder=10)
        plt.plot(Dist/1000, SegmentedElevation, '-', lw=2, c=ColourMap(Colour),zorder=9)
    
    # Finalise the figure
    plt.xlabel('Distance (km)')
    plt.ylabel('Elevation (m)')
    plt.title('Basin ID ' + str(BasinID))
    plt.tight_layout()
    #add colourbar
    CAx = Fig.add_axes([0.15,0.8,0.4,0.05])
    m = cm.ScalarMappable(cmap=ColourMap)
    m.set_array(ChannelData.m_chi)
    plt.colorbar(m, cax=CAx,orientation='horizontal')
    plt.xlabel('$M_{\chi}$ m$^{0.64}$')
    #save output
    plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_LongProfMChi.png", dpi=300)
    plt.close() 
Example 28
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 4 votes vote down vote up
def PlotEStarRStar(Basin, Sc=0.71):
    """
    MDH
    """
    
    Data = CalculateEStarRStar(Basin)
    
    # setup the figure
    Fig = CreateFigure(AspectRatio=1.2)
        
    #choose colormap
    ColourMap = cm.viridis

    #Plot analytical relationship
    PlotEStarRStarTheoretical()
    
    # colour code by flow length
    MinFlowLength = Data.FlowLength.min()
    Data.FlowLength = Data.FlowLength-MinFlowLength
    MaxFlowLength = Data.FlowLength.max()
    colours = (Data.FlowLength/MaxFlowLength)
    
    #plot the data
    plt.loglog()
    
    # Error bars with colours but faded (alpha)
    for i, row in Data.iterrows(): 
        EStarErr = np.array([[row.EStarLower],[row.EStarUpper]])
        RStarErr = np.array([[row.RStarLower],[row.RStarUpper]])
        plt.plot([row.EStar,row.EStar],RStarErr,'-', lw=1, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
        plt.plot(EStarErr,[row.RStar,row.RStar],'-', lw=1, color=ColourMap(colours[i]), alpha=0.5,zorder=9)
        plt.plot(row.EStar,row.RStar,'o',ms=4,color=ColourMap(colours[i]),zorder=32)

    # Finalise the figure
    plt.xlabel('$E^*={{-2\:C_{HT}\:L_H}/{S_C}}$')
    plt.ylabel('$R^*=S/S_C$')
    plt.xlim(0.1,1000)
    plt.ylim(0.01,1.5)
        
    # add colour bar
    m = cm.ScalarMappable(cmap=ColourMap)
    m.set_array(Data.FlowLength)
    cbar = plt.colorbar(m)
    tick_locator = ticker.MaxNLocator(nbins=5)
    cbar.locator = tick_locator
    cbar.update_ticks()
    cbar.set_label('Distance to Outlet (m)')
    
    plt.suptitle("Basin "+str(Basin)+" Dimensionless Hillslope Morphology")
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    plt.savefig(PlotDirectory+FilenamePrefix + "_" + "%02d" % Basin + "_EStarRStar.png", dpi=300)
    plt.close(Fig) 
Example 29
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_HillslopeMorphology.py    MIT License 4 votes vote down vote up
def PlotKsnAgainstRStar(DataDirectory, FilenamePrefix, PlotDirectory):
    """
    Function to plot median Ksn against R* for a series of basins

    Author: FJC
    """

    # SMM: What generates this file?? I don't have it.
    input_csv = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
    df = pd.read_csv(input_csv)

    # linregress
    slope, intercept, r_value, p_value, std_err = stats.linregress(df['mchi_median'],df['Rstar_median'])
    print(slope, intercept, r_value, p_value)
    x = np.linspace(0, 200, 100)
    new_y = slope*x + intercept

    # set up the figure
    fig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, figsize=(5,5))

    ax.scatter(df['mchi_median'], df['Rstar_median'], c=df['basin_keys'], s=50, edgecolors='k', zorder=100, cmap=cm.viridis)
    ax.errorbar(df['mchi_median'], df['Rstar_median'], xerr=[df['mchi_lower_err'], df['mchi_upper_err']], yerr=[df['Rstar_lower_err'], df['Rstar_upper_err']], fmt='o', ecolor='0.5',markersize=1,mfc='white',mec='k')
    # ax.text(0.55, 0.1, '$y = $'+str(np.round(slope,4))+'$x + $'+str(np.round(intercept,2))+'\n$R^2 = $'+str(np.round(r_value,2))+'\n$p = $'+str(p_value), fontsize=9, color='black', transform=ax.transAxes)
    ax.plot(x, new_y, c='0.5', ls='--')
    ax.set_xlim(0,100)

    ax.set_xlabel('$k_{sn}$')
    ax.set_ylabel('$R*$')

    plt.subplots_adjust(left=0.15,right=0.85, bottom=0.1, top=0.95)
    CAx = fig.add_axes([0.87,0.1,0.02,0.85])
    m = cm.ScalarMappable(cmap=cm.viridis)
    m.set_array(df['basin_keys'])
    plt.colorbar(m, cax=CAx,orientation='vertical', label='Basin key')

    #plt.tight_layout()

    #save output
    plt.savefig(PlotDirectory+FilenamePrefix +"_ksn_vs_rstar.png", dpi=300)
    plt.clf()


# This seems to do the same as the PlotEStarRStarWithinBasin function!!!
# However it is not working since I don't have the _basin_hillslope_data.csv' file 
Example 30
Project: gaia_tools   Author: jobovy   File: tgasSelect.py    MIT License 4 votes vote down vote up
def plot_cmd(self,type='sf',cut=True):
        """
        NAME:
           plot_cmd
        PURPOSE:
           Plot the distribution of counts in the color-magnitude diagram
        INPUT:
           type= ('sf') Plot 'sf': selection function
                             'tgas': TGAS counts
                             '2mass': 2MASS counts
           cut= (True) cut to the 'good' part of the sky
        OUTPUT:
           Plot to output device
        HISTORY:
           2017-01-17 - Written - Bovy (UofT/CCA)
        """
        jtbins= (numpy.amax(_2mc[0])-numpy.amin(_2mc[0]))/0.1+1
        nstar2mass, edges= numpy.histogramdd(\
            _2mc[:3].T,bins=[jtbins,3,_BASE_NPIX],
            range=[[numpy.amin(_2mc[0])-0.05,numpy.amax(_2mc[0])+0.05],
                   [-0.05,1.0],[-0.5,_BASE_NPIX-0.5]],weights=_2mc[3])
        findx= (self._full_jk > -0.05)*(self._full_jk < 1.0)\
            *(self._full_twomass['j_mag'] < 13.5)
        nstartgas, edges= numpy.histogramdd(\
            numpy.array([self._full_jt[findx],self._full_jk[findx],\
                             (self._full_tgas['source_id'][findx]\
                                  /2**(35.+2*(12.-numpy.log2(_BASE_NSIDE))))\
                             .astype('int')]).T,
            bins=[jtbins,3,_BASE_NPIX],
            range=[[numpy.amin(_2mc[0])-0.05,numpy.amax(_2mc[0])+0.05],
                   [-0.05,1.0],[-0.5,_BASE_NPIX-0.5]])
        if cut:
            nstar2mass[:,:,self._exclude_mask_skyonly]= numpy.nan
            nstartgas[:,:,self._exclude_mask_skyonly]= numpy.nan
        nstar2mass= numpy.nansum(nstar2mass,axis=-1)
        nstartgas= numpy.nansum(nstartgas,axis=-1)
        if type == 'sf':
            pt= nstartgas/nstar2mass
            vmin= 0.
            vmax= 1.
            zlabel=r'$\mathrm{completeness}$'
        elif type == 'tgas' or type == '2mass':
            vmin= 0.
            vmax= 6.
            zlabel= r'$\log_{10}\mathrm{number\ counts}$'
            if type == 'tgas':
                pt= numpy.log10(nstartgas)
            elif type == '2mass':
                pt= numpy.log10(nstar2mass)
        return bovy_plot.bovy_dens2d(pt,origin='lower',
                                     cmap='viridis',interpolation='nearest',
                                     colorbar=True,shrink=0.78,
                                     vmin=vmin,vmax=vmax,zlabel=zlabel,
                                     yrange=[edges[0][0],edges[0][-1]],
                                     xrange=[edges[1][0],edges[1][-1]],
                                     xlabel=r'$J-K_s$',
                                     ylabel=r'$J+\Delta J$') 
Example 31
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: image.py    MIT License 4 votes vote down vote up
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
           origin=None, dpi=100):
    """
    Save an array as in image file.

    The output formats available depend on the backend being used.

    Parameters
    ----------
    fname : str or file-like
        Path string to a filename, or a Python file-like object.
        If *format* is *None* and *fname* is a string, the output
        format is deduced from the extension of the filename.
    arr : array-like
        An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
    vmin, vmax: [ None | scalar ]
        *vmin* and *vmax* set the color scaling for the image by fixing the
        values that map to the colormap color limits. If either *vmin*
        or *vmax* is None, that limit is determined from the *arr*
        min/max value.
    cmap : matplotlib.colors.Colormap, optional
        For example, ``cm.viridis``.  If ``None``, defaults to the
        ``image.cmap`` rcParam.
    format : str
        One of the file extensions supported by the active backend.  Most
        backends support png, pdf, ps, eps and svg.
    origin : [ 'upper' | 'lower' ]
        Indicates whether the ``(0, 0)`` index of the array is in the
        upper left or lower left corner of the axes.  Defaults to the
        ``image.origin`` rcParam.
    dpi : int
        The DPI to store in the metadata of the file.  This does not affect the
        resolution of the output image.
    """
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    if isinstance(fname, getattr(os, "PathLike", ())):
        fname = os.fspath(fname)
    if (format == 'png'
        or (format is None
            and isinstance(fname, six.string_types)
            and fname.lower().endswith('.png'))):
        image = AxesImage(None, cmap=cmap, origin=origin)
        image.set_data(arr)
        image.set_clim(vmin, vmax)
        image.write_png(fname)
    else:
        fig = Figure(dpi=dpi, frameon=False)
        FigureCanvas(fig)
        fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
                     resize=True)
        fig.savefig(fname, dpi=dpi, format=format, transparent=True) 
Example 32
Project: LevelSetFusion-Python   Author: Algomorph   File: visualization.py    Apache License 2.0 4 votes vote down vote up
def make_3d_plots(canonical_field, live_field):
    """
    Makes a 3D plot of the live sdf, with the SDF value plotted along the (vertical) Z axis
    :param canonical_field: canonical (source) SDF field
    :param live_field: warped/transformed live (target) SDF field
    :return: image (numpy array) of the 3D plot
    """
    # plot warped live field
    fig = plt.figure(figsize=(16, 10))
    fig.canvas.mpl_connect('key_press_event', exit_func)
    ax = fig.gca(projection='3d')

    # Make live data.
    x_grid = np.arange(0, live_field.shape[0])
    y_grid = np.arange(0, live_field.shape[1])

    x_grid, y_grid = np.meshgrid(x_grid, y_grid)

    # Chop of "unknowns" from both sides
    x_start = 9
    x_end = 109
    x_grid_cropped = x_grid[:, x_start:x_end]
    y_grid_cropped = y_grid[:, x_start:x_end]
    live_z = live_field * 10
    live_z_cropped = live_z[:, x_start:x_end, ]

    # Plot the surface.
    surf = ax.plot_surface(x_grid_cropped, y_grid_cropped, live_z_cropped, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False, shade=True, rcount=128, ccount=x_start - x_end)

    canonical_z = canonical_field * 10
    canonical_z_cropped = canonical_z[:, x_start: x_end]

    # colors = cm.viridis(canonical_z_cropped)
    wire = ax.plot_wireframe(x_grid_cropped, y_grid_cropped, canonical_z_cropped, rcount=128, linestyles='solid',
                             linewidth=0.7, ccount=x_start - x_end, color=(0, 0, 0, 0.5))
    # Customize the z axis.
    ax.set_zlim(-10.5, 10.05)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.view_init(20, 30)

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    fig.canvas.draw()

    plot_image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    plot_image = plot_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    plot_image = plot_image[150:870, 200:1430]
    plt.close(fig)
    return plot_image 
Example 33
Project: mrf-reconstruction-midl2019   Author: fabianbalsiger   File: plt_qualitative.py    MIT License 4 votes vote down vote up
def plot_2d_image_colorbar(path: str, image: np.ndarray, cmap=cm.get_cmap('Greys'),
                           min_value: float=None, max_value: float=None, plot_image_size: int=10):
    """Plots a 2-D image with a color bar to the right.

    See Also:
        Matplotlib colormaps: https://matplotlib.org/examples/color/colormaps_reference.html.
        Please use a perceptually uniform colormap like cm.viridis, cm.plasma, cm.inferno, or cm.magma.

    Args:
        path (str): The full path to save the plot.
        image (np.ndarray): The 2-D image.
        cmap (colormap): The color map.
        min_value (float): The min value of the color map. If None, then use the data's min value.
        max_value (float): The max value of the color map. If None, then use the data's max value.
        plot_image_size (int): The size of the image in inches. If the image is not rectangular, the longer size will
            be of dimension plot_image_size. Note that the width of the final figure will be larger than plot_image_size
            due to the colorbar.

    Returns:
        None.
    """

    # calculate figure size, unit is inches
    y, x = image.shape
    if x > y:
        y = y / x * plot_image_size
        x = plot_image_size
    elif y > x:
        x = x / y * plot_image_size
        y = plot_image_size
    else:
        x = y = plot_image_size
    width_of_colorbar = 2  # we need two inches of space for the colorbar
    x = x + width_of_colorbar
    colorbar_begin = 1 - width_of_colorbar / x

    fig = plt.figure(figsize=(x, y))  # add 1 to width for colorbar
    ax = fig.add_axes([0, 0, colorbar_begin, 1])
    ax.set_axis_off()
    ax.margins(0)
    img = ax.imshow(image, interpolation='nearest', cmap=cmap)
    cax = fig.add_axes([colorbar_begin + 0.01, 0.05, width_of_colorbar / x / 3, 0.9])
    cb = fig.colorbar(img, cax=cax)

    # adjust min and max if provided
    if min_value or max_value:
        min_, max_ = img.get_clim()
        min_ = min_value if min_value else min_
        max_ = max_value if max_value else max_
        img.set_clim(min_, max_)
        cb.set_clim(min_, max_value)
    cb.ax.tick_params(labelsize=20)

    plt.savefig(path, transparent=True)
    plt.close() 
Example 34
Project: scalable-irl   Author: makokal   File: puddle_world.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _plot_graph_in_world(self, G, policies, show_edges):
        """ Shows the lattest version of the world with MDP
        """
        gna = G.gna
        values = [gna(n, 'V') for n in G.nodes]
        nv = mpl.colors.Normalize(vmin=min(values), vmax=max(values))
        cmapping = cm.ScalarMappable(norm=nv, cmap=cm.viridis)

        best_nodes = set()
        for traj in policies:
            for state in traj:
                best_nodes.add(state)

        for i, n in enumerate(G.nodes):
            posx, posy = gna(n, 'data')
            if gna(n, 'type') == 'start':
                color = 'black'
                nr = 1.0
            elif self.terminal((posx, posy)):
                color = 'green'
                nr = 1.5
            elif n in best_nodes:
                color = 'green'
                nr = 0.5
            else:
                color = cmapping.to_rgba(gna(n, 'V'))
                nr = 0.5
            self.ax.add_artist(Circle((posx, posy), nr/100., fc=color,
                               ec=color, lw=1.5, zorder=3))

            p = gna(n, 'pi')
            ndata = gna(n, 'data')
            for i, e in enumerate(G.out_edges(n)):
                tdata = gna(e[1], 'data')
                x1, y1 = ndata[0], ndata[1]
                x2, y2 = tdata[0], tdata[1]

                if n in best_nodes and i == p:
                    self.ax.plot((x1, x2), (y1, y2), ls='-',
                                 lw=2.0, c='g', zorder=3)
                else:
                    if show_edges:
                        self.ax.plot((x1, x2), (y1, y2), ls='-', lw=1.0,
                                     c='0.7', alpha=0.5)

######################################################################## 
Example 35
Project: Blackjack-Tracker   Author: martinabeleda   File: image.py    MIT License 4 votes vote down vote up
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
           origin=None, dpi=100):
    """
    Save an array as in image file.

    The output formats available depend on the backend being used.

    Parameters
    ----------
    fname : str or file-like
        Path string to a filename, or a Python file-like object.
        If *format* is *None* and *fname* is a string, the output
        format is deduced from the extension of the filename.
    arr : array-like
        An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
    vmin, vmax: [ None | scalar ]
        *vmin* and *vmax* set the color scaling for the image by fixing the
        values that map to the colormap color limits. If either *vmin*
        or *vmax* is None, that limit is determined from the *arr*
        min/max value.
    cmap : matplotlib.colors.Colormap, optional
        For example, ``cm.viridis``.  If ``None``, defaults to the
        ``image.cmap`` rcParam.
    format : str
        One of the file extensions supported by the active backend.  Most
        backends support png, pdf, ps, eps and svg.
    origin : [ 'upper' | 'lower' ]
        Indicates whether the ``(0, 0)`` index of the array is in the
        upper left or lower left corner of the axes.  Defaults to the
        ``image.origin`` rcParam.
    dpi : int
        The DPI to store in the metadata of the file.  This does not affect the
        resolution of the output image.
    """
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure

    # Fast path for saving to PNG
    if (format == 'png' or format is None or
            isinstance(fname, six.string_types) and
            fname.lower().endswith('.png')):
        image = AxesImage(None, cmap=cmap, origin=origin)
        image.set_data(arr)
        image.set_clim(vmin, vmax)
        image.write_png(fname)
    else:
        fig = Figure(dpi=dpi, frameon=False)
        FigureCanvas(fig)
        fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
                     resize=True)
        fig.savefig(fname, dpi=dpi, format=format, transparent=True) 
Example 36
Project: karabo_data   Author: European-XFEL   File: __init__.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_data(self,
                  modules_data, *,
                  axis_units='px',
                  frontview=True,
                  ax=None,
                  figsize=None,
                  colorbar=False,
                  **kwargs):
        """Implementation for plot_data_fast
        """
        from matplotlib.cm import viridis
        import matplotlib.pyplot as plt

        if axis_units not in {'px', 'm'}:
            raise ValueError("axis_units must be 'px' or 'm', not {!r}"
                             .format(axis_units))

        res, centre = self.position_modules(modules_data)
        min_y, min_x = -centre
        max_y, max_x = np.array(res.shape) - centre

        _extent = np.array((min_x - 0.5, max_x + 0.5, min_y - 0.5, max_y + 0.5))
        cross_size = 20
        if axis_units == 'm':
            _extent *= self.geom.pixel_size
            cross_size *= self.geom.pixel_size

        # Use a dark grey for missing data
        _cmap = copy(viridis)
        _cmap.set_bad('0.25', 1.0)

        kwargs.setdefault('cmap', _cmap)
        kwargs.setdefault('extent', _extent)
        kwargs.setdefault('origin', 'lower')

        if ax is None:
            fig = plt.figure(figsize=figsize or (10, 10))
            ax = fig.add_subplot(1, 1, 1)

        im = ax.imshow(res, **kwargs)
        if isinstance(colorbar, dict) or colorbar is True:
            if isinstance(colorbar, bool):
                colorbar = {}
            colorbar = plt.colorbar(im, ax=ax, **colorbar)

        ax.set_xlabel('metres' if axis_units == 'm' else 'pixels')
        ax.set_ylabel('metres' if axis_units == 'm' else 'pixels')

        if frontview:
            ax.invert_xaxis()

        # Draw a cross at the centre
        ax.hlines(0, -cross_size, +cross_size, colors='w', linewidths=1)
        ax.vlines(0, -cross_size, +cross_size, colors='w', linewidths=1)
        return ax