Python matplotlib.pyplot.ticklabel_format() Examples

The following are code examples for showing how to use matplotlib.pyplot.ticklabel_format(). 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: fast15-paper-extras   Author: zdvresearch   File: analyze_NEW_CATEGORIES_SIZE_JSON_DATA.py    MIT License 6 votes vote down vote up
def plot_delgetput_total_bytes_permonth(del_array, put_array, get_array, tags_r, x_axis_r):

    plt.figure(figsize=(tags_r.__len__(), 11))
    plt.xticks(x_axis_r, tags_r, rotation=70)
    plt.yticks(fontsize=20)
    #plt.title('# Operations per month', fontsize=30)
    #plt.xlabel('Months', fontsize=20)
    plt.ylabel('MB moved', fontsize=20)
    plt.grid(True)

    plt.plot(x_axis_r, del_array, color='0', label='delete', marker='o', linestyle='-', linewidth=2)
    plt.plot(x_axis_r, put_array, color='0', label='put', marker='s', linestyle='--', linewidth=2)
    plt.plot(x_axis_r, get_array, color='0', label='get', marker='x', linestyle=':', linewidth=2)
    plt.legend(loc='upper right', fontsize=20)
    plt.subplots_adjust(top=.91)
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    #plt.show()
    plt.savefig('bytes_del_get_put_foreverymonth.pdf')
    plt.close() 
Example 2
Project: data-science-from-scratch   Author: kevntao   File: visualizing_data.py    The Unlicense 6 votes vote down vote up
def make_chart_misleading_y_axis(plt, mislead=True):

    mentions = [500, 505]
    years = [2013, 2014]

    plt.bar([2012.6, 2013.6], mentions, 0.8)
    plt.xticks(years)
    plt.ylabel("# of times I heard someone say 'data science'")

    # if you don't do this, matplotlib will label the x-axis 0, 1
    # and then add a +2.013e3 off in the corner (bad matplotlib!)
    plt.ticklabel_format(useOffset=False)

    if mislead:
        # misleading y-axis only shows the part above 500
        plt.axis([2012.5,2014.5,499,506])
        plt.title("Look at the 'Huge' Increase!")
    else:
        plt.axis([2012.5,2014.5,0,550])
        plt.title("Not So Huge Anymore.")       
    plt.show() 
Example 3
Project: mapper-tda   Author: ksanjeevan   File: em_3d_help.py    MIT License 6 votes vote down vote up
def plot_clustering_3d(obj, data_local, data_global, filename):


    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')

    colors = get_colors(len(obj.c_to_ind))

    ax.plot(*zip(*data_global), marker='o', color='k', ls='', ms=4., mew=1.0, alpha=0.4, mec='none')

    for i,c in enumerate(obj.c_to_ind):
        ax.plot(*zip(*data_local[obj.c_to_ind[c]]), marker='o', color=colors[i], ls='', ms=4., mew=1.0, alpha=0.8, mec='none')
        

    plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    ax.view_init(*params.ANGLE)
    #plt.grid(True)
    #ax.set_axis_bgcolor('grey')


    
    fig.savefig(filename, format='png')

    plt.close() 
Example 4
Project: mapper-tda   Author: ksanjeevan   File: em_help.py    MIT License 6 votes vote down vote up
def plot_clustering(obj, data, filename, axis_str=('', ''), tit_str_add='', anot=None):

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)

    colors = get_colors(len(obj.c_to_ind))

    for i,c in enumerate(obj.c_to_ind):
        plt.plot(*zip(*data[obj.c_to_ind[c]]), marker='o', color=colors[i], ls='', ms=4., mew=1.0, alpha=0.8, mec='none')

    plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    #plt.grid(True)
    #ax.set_axis_bgcolor('grey')
    plt.xlabel(axis_str[0])
    plt.ylabel(axis_str[1])
    fig.savefig(filename, format='png')

    plt.close() 
Example 5
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 6 votes vote down vote up
def plot_ng_chain_ratio_derivative_history(ratio_evolution, ratio_derivative_dict, history_mid_fluence, sampled_index):

	ratio_name_list = ratio_evolution[1]

	sampled_history_fluence = sample_data_with_sample_indexes(sampled_index, history_mid_fluence)

	fig, ax = plt.subplots()
	count = 0
	linestyle = '-'
	for i in range(len(ratio_name_list)):
		if count > 8:
			linestyle = ':'
		ratio_name = ratio_name_list[i]
		ratio_derivative = ratio_derivative_dict[ratio_name]
		sampled_ratio_derivative = sample_data_with_sample_indexes(sampled_index, ratio_derivative)
		plt.plot(sampled_history_fluence, sampled_ratio_derivative, linestyle = linestyle, label = ratio_name)
		count += 1
	plt.ylabel('Ratio derivative', fontsize=16)
	plt.grid()
	ax.yaxis.get_offset_text().set_fontsize(16)
	plt.legend(prop={'size': 15})
	plt.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	plt.tick_params(labelsize=15)
	plt.xlabel('Fluence', fontsize=16)
	plt.show() 
Example 6
Project: praktipy   Author: The-Ludwig   File: praktiplot.py    MIT License 5 votes vote down vote up
def cla():
    plt.cla()
    plt.ticklabel_format(useLocale=True) 
Example 7
Project: praktipy   Author: The-Ludwig   File: praktiplot.py    MIT License 5 votes vote down vote up
def cla():
    """
    Calls the matplotlib plt.cla, but turns the useLocale option back on.
    """
    plt.cla()
    plt.ticklabel_format(useLocale=True)

## Use fast settings as default 
Example 8
Project: ml-eeg   Author: pbrusco   File: visualizations.py    GNU General Public License v3.0 5 votes vote down vote up
def lines(features_table, title=""):
    plt.figure()

    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    for idx, row in features_table.iterrows():
        alpha = row.window_size / features_table.window_size.max()
        plt.hlines(y=row.feature_importances_folds_mean, lw=5, alpha=alpha, xmin=row.starting_time, xmax=row.end_time)

    plt.ylim([features_table.feature_importances_folds_mean.min(), features_table.feature_importances_folds_mean.max()])
    plt.xlim([features_table.starting_time.min(), features_table.end_time.max()])
    plt.draw() 
Example 9
Project: ml-eeg   Author: pbrusco   File: visualizations.py    GNU General Public License v3.0 5 votes vote down vote up
def window_bars(features_table, title="", fontsize=20):
    features_table.sort_values(["window_size", "starting_time"], ascending=False, inplace=True)
    fig = plt.figure()
    ax = fig.add_subplot(111)

    cmap = matplotlib.cm.get_cmap('Greys')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    vmin, vmax = (features_table.feature_importances_folds_mean.min(), features_table.feature_importances_folds_mean.max())
    norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)

    for idx, (_, row) in enumerate(features_table.iterrows()):
        val = row.feature_importances_folds_mean
        # plt.hlines(y=idx, lw=3, color=cmap(norm(val)), xmin=row.starting_time, xmax=row.end_time)
        p = patches.Rectangle(
            (row.starting_time, idx),  # (x, y)
            row.window_size,  # width
            1,  # height
            facecolor=cmap(norm(val)),
            # edgecolor="blue"
        )
        ax.add_patch(p)

    ax.set_title(title, fontsize=fontsize)
    plt.xlim([features_table.starting_time.min(), features_table.end_time.max()])
    plt.ylim([-1, len(features_table) + 2])

    divider = make_axes_locatable(ax)
    ax_colorbar = divider.append_axes('right', size='60%', pad=0.01)

    img = plt.imshow(np.array([[vmin, vmax]]), cmap=cmap)
    img.set_visible(False)
    plt.colorbar(img, cax=ax_colorbar, orientation="vertical")

    plt.draw() 
Example 10
Project: benchmarks   Author: tensorflow   File: plot_process_info.py    Apache License 2.0 5 votes vote down vote up
def visualize(file_path):

  entries = []
  with open(file_path) as f:
    entries = [json.loads(line) for line in f.readlines() if line.strip()]

  if not entries:
    print('There is no data in file {}'.format(file_path))
    return

  pdf = backend_pdf.PdfPages("process_info.pdf")
  idx = 0
  names = [name for name in entries[0].keys() if name != 'time']
  times = [entry['time'] for entry in entries]

  for name in names:
    values = [entry[name] for entry in entries]
    fig = plt.figure()
    ax = plt.gca()
    ax.yaxis.set_major_formatter(tick.ScalarFormatter(useMathText=True))
    plt.ticklabel_format(style='sci', axis='y', scilimits=(-2,3))
    plt.plot(times, values, colors[idx % len(colors)], marker='x', label=name)
    plt.xlabel('Time (sec)')
    plt.ylabel(name)
    plt.ylim(ymin=0)
    plt.legend(loc = 'upper left')
    pdf.savefig(fig)
    idx += 1

  plt.show()
  pdf.close()
  print('Generated process_info.pdf from {}'.format(file_path)) 
Example 11
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def mean_output_rate_time_evolution(self, end_frame=None,
                                        n_individual_plots=0):
        # mpl.style.use('ggplot')
        output_rates = self.get_output_rates_over_all_psps()
        mean = np.nanmean(output_rates, axis=0)[:end_frame]
        std = np.nanstd(output_rates, axis=0)[:end_frame]
        time = (np.arange(0, len(output_rates[0]))
                * self.params['sim']['every_nth_step_weights']
                * self.params['sim']['dt'])[:end_frame]
        plt.plot(time, mean)
        plt.fill_between(time,
                         mean + std,
                         mean - std, alpha=0.5)
        # Plot some invidivual traces
        for j in np.arange(n_individual_plots):
            plt.plot(time, output_rates[j][:end_frame])
        # plt.ylim([-0.5, 1.0])
        plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 0)) 
Example 12
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def grid_score_time_correlation(self, row_index=0):
        plt.figure(figsize=(14, 5))
        mpl.style.use('ggplot')
        gs = gridspec.GridSpec(1, 4)
        gs_dict = {(0, 0): 0, (0, 1): 1, (1, 0): 2, (1, 1): 3}
        methods = ['Weber', 'sargolini']
        for i, method in enumerate(methods):
            for k, ncum in enumerate([1, 10]):
                column_index = gs_dict[(i, k)]
                plt.subplot(gs[row_index, column_index])
                grid_scores = self.get_list_of_grid_score_arrays_over_all_psps(
                                method=method, n_cumulative=ncum)
                time = (np.arange(0, len(grid_scores[0]))
                        * self.params['sim']['every_nth_step_weights']
                        * self.params['sim']['dt'])
                # Plot some invidivual traces
                start_frame = 100
                correlograms = []
                for j in np.arange(4):
                    # corr_time = time[start_frame:]
                    corr_grid_scores = grid_scores[j][start_frame:]
                    correlogram = scipy.signal.correlate(corr_grid_scores,
                                                         corr_grid_scores,
                                                         mode='same')
                    # correlograms.append(correlogram)
                    plt.plot(correlogram)
                plt.plot(np.mean(correlograms, axis=0))
                # plt.ylim([-0.5, 1.0])
                plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 0))
                if row_index == 0:
                    plt.title('{0}, nc = {1}'.format(method, ncum), fontsize=10) 
Example 13
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def grid_score_hexagonal_and_quadratic(self, n_individual_plots=1,
                                           method='sargolini', n_cumulative=3,
                                           end_frame=None):
        """
        Convenience function
        """
        plt.figure(figsize=(14, 6))
        mpl.style.use('ggplot')
        color_cycle = dict(hexagonal=color_cycle_blue3,
                           quadratic=color_cycle_red3)
        for type in ['hexagonal', 'quadratic']:
            grid_scores = self.get_list_of_grid_score_arrays_over_all_psps(
                                    method=method, n_cumulative=n_cumulative, type=type)
            time = (np.arange(0, len(grid_scores[0]))
                            * self.params['sim']['every_nth_step_weights']
                            * self.params['sim']['dt'])[:end_frame]
            for j in np.arange(n_individual_plots):
                plt.plot(time, grid_scores[j][:end_frame],
                         color=color_cycle[type][j], label=type[:4])

        plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 0))
        plt.legend(loc='best')
        # self.mean_grid_score_time_evolution(end_frame=200, n_individual_plots=1,
        # 									methods=['sargolini'],
        # 									type='hexagonal', row_index=0,
        # 									n_cumulative=[10])
        # self.mean_grid_score_time_evolution(end_frame=200, n_individual_plots=1,
        # 									methods=['sargolini'],
        # 									type='quadratic', row_index=1,
        # 									n_cumulative=[10]) 
Example 14
Project: ocelot   Author: ocelot-collab   File: genesis_plot.py    GNU General Public License v3.0 5 votes vote down vote up
def subfig_z_energy_espread_bunching(ax_energy, g, zi=None, x_units='um', legend=False, *args, **kwargs):
    ax_energy.clear()
    number_ticks = 6

    if x_units == 'um':
        ax_energy.set_xlabel(r's [$\mu$m]')
        x = g.t * speed_of_light * 1.0e-15 * 1e6
    elif x_units == 'fs':
        ax_energy.set_xlabel(r't [fs]')
        x = g.t
    else:
        raise ValueError('Unknown parameter x_units (should be um or fs)')

    if zi == None:
        zi = -1

    ax_energy.plot(x, g.el_energy[:, zi] * m_e_GeV, 'b-', x, (g.el_energy[:, zi] + g.el_e_spread[:, zi]) * m_e_GeV,
                   'r--', x, (g.el_energy[:, zi] - g.el_e_spread[:, zi]) * m_e_GeV, 'r--')
    ax_energy.set_ylabel(r'$E\pm\sigma_E$ [GeV]')
    # ax_energy.ticklabel_format(axis='y', style='sci', scilimits=(-3, 3), useOffset=False)
    ax_energy.ticklabel_format(useOffset=False, style='plain')
    ax_energy.grid(kwargs.get('grid', True))
    # plt.yticks(plt.yticks()[0][0:-1])

    ax_bunching = ax_energy.twinx()
    ax_bunching.plot(x, g.bunching[:, zi], 'grey', linewidth=0.5)
    ax_bunching.set_ylabel('Bunching')
    ax_bunching.set_ylim(ymin=0)
    ax_bunching.grid(False)

    ax_energy.yaxis.major.locator.set_params(nbins=number_ticks)
    ax_bunching.yaxis.major.locator.set_params(nbins=number_ticks)

    ax_energy.tick_params(axis='y', which='both', colors='b')
    ax_energy.yaxis.label.set_color('b')

    ax_bunching.tick_params(axis='y', which='both', colors='grey')
    ax_bunching.yaxis.label.set_color('grey')

    ax_energy.set_xlim([x[0], x[-1]]) 
Example 15
Project: ocelot   Author: ocelot-collab   File: genesis_plot.py    GNU General Public License v3.0 5 votes vote down vote up
def subfig_z_energy_espread(ax_energy, g, zi=None, x_units='um', legend=False, *args, **kwargs):
    ax_energy.clear()
    number_ticks = 6

    if x_units == 'um':
        ax_energy.set_xlabel(r's [$\mu$m]')
        x = g.t * speed_of_light * 1.0e-15 * 1e6
    elif x_units == 'fs':
        ax_energy.set_xlabel(r't [fs]')
        x = g.t
    else:
        raise ValueError('Unknown parameter x_units (should be um or fs)')

    if zi == None:
        zi = -1

    ax_energy.plot(x, g.el_energy[:, zi] * m_e_GeV, 'b-', x, (g.el_energy[:, zi] + g.el_e_spread[:, zi]) * m_e_GeV,
                   'r--', x, (g.el_energy[:, zi] - g.el_e_spread[:, zi]) * m_e_GeV, 'r--')
    ax_energy.set_ylabel(r'$E\pm\sigma_E$ [GeV]')
    # ax_energy.ticklabel_format(axis='y', style='sci', scilimits=(-3, 3), useOffset=False)
    ax_energy.ticklabel_format(useOffset=False, style='plain')
    ax_energy.grid(kwargs.get('grid', True))
    # plt.yticks(plt.yticks()[0][0:-1])

    ax_energy.yaxis.major.locator.set_params(nbins=number_ticks)
    ax_energy.tick_params(axis='y', which='both', colors='b')
    ax_energy.yaxis.label.set_color('b')

    ax_energy.set_xlim([x[0], x[-1]]) 
Example 16
Project: ocelot   Author: ocelot-collab   File: genesis_plot.py    GNU General Public License v3.0 5 votes vote down vote up
def subfig_evo_el_energy(ax_energy, g, legend, **kwargs):
    number_ticks = 6

    el_energy = g.el_energy * m_e_MeV
    el_energy_av = int(np.mean(el_energy))
    ax_energy.plot(g.z, np.average(el_energy - el_energy_av, axis=0), 'b-', linewidth=1.5)
    ax_energy.set_ylabel('E + ' + str(el_energy_av) + '[MeV]')
    ax_energy.ticklabel_format(axis='y', style='sci', scilimits=(-3, 3), useOffset=False)
    ax_energy.grid(kwargs.get('grid', True))

    ax_spread = ax_energy.twinx()
    ax_spread.plot(g.z, np.average(g.el_e_spread * m_e_GeV * 1000, weights=g.I, axis=0), 'm--', g.z,
                   np.amax(g.el_e_spread * m_e_GeV * 1000, axis=0), 'r--', linewidth=1.5)
    ax_spread.set_ylabel(r'$\sigma_E$ [MeV]')
    ax_spread.grid(False)
    ax_spread.set_ylim(ymin=0)

    ax_energy.yaxis.major.locator.set_params(nbins=number_ticks)
    ax_spread.yaxis.major.locator.set_params(nbins=number_ticks)

    ax_energy.tick_params(axis='y', which='both', colors='b')
    ax_energy.yaxis.label.set_color('b')
    ax_spread.tick_params(axis='y', which='both', colors='r')
    ax_spread.yaxis.label.set_color('r') 
Example 17
Project: metatlas   Author: biorack   File: dill2plots.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_lin_log(self,label):
        self.ax.set_yscale(label)
        self.ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        self.fig.canvas.draw_idle() 
Example 18
Project: metatlas   Author: biorack   File: dill2plots.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_lin_log(self,label):
        self.ax.set_yscale(label)
        self.ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        self.fig.canvas.draw_idle() 
Example 19
Project: fast15-paper-extras   Author: zdvresearch   File: analyze_NEW_CATEGORIES_SIZE_JSON_DATA.py    MIT License 5 votes vote down vote up
def plot_delgetput_total_count_permonth(del_array, put_array, get_array, tags_r, x_axis_r, outfilename_j):

    plt.figure(figsize=(tags_r.__len__(), 11))
    plt.xticks(x_axis_r, tags_r, rotation=70)
    plt.yticks(fontsize=20)
    #plt.title('# Operations per month', fontsize=30)
    #plt.xlabel('Months', fontsize=20)
    plt.ylabel('# operations ($\cdot 10^6$)', fontsize=20)
    plt.grid(True)

    plt.plot(x_axis_r, del_array, color='0', label='delete', marker='o', linestyle='-', linewidth=2)
    plt.plot(x_axis_r, put_array, color='0', label='put', marker='s', linestyle='--', linewidth=2)
    plt.plot(x_axis_r, get_array, color='0', label='get', marker='x', linestyle=':', linewidth=2)
    plt.legend(loc='upper right', fontsize=20)
    plt.subplots_adjust(top=.91)
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    #plt.show()
    plt.savefig(outfilename_j)
    plt.close()


#########################
    ##### plot on the same plot bytes of del, put, get per month (x axis = months, y axis = count) 
Example 20
Project: NICERsoft   Author: paulray   File: plotutils.py    MIT License 5 votes vote down vote up
def plot_deadtime(etable):
    'Plot histogram of detector deadtime in microseconds.'
    us = etable['DEADTIME']*1.0e6
    # Bin at 1 us resolution
    max = np.floor(us.max())+1
    plot.hist(us,range=(0.0,max), bins=int(max),log=True)
    #plot.ticklabel_format(style = 'sci', axis='x', scilimits = (0,0))
    plot.title('Histogram of deadtime')
    plot.xlabel('Deadtime [microseconds]')
    plot.ylabel('Frequency [occurrences]')

    return

#-------------------------PULSE PROFILE---------------------------------- 
Example 21
Project: TXPipe   Author: LSSTDESC   File: psf_diagnostics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_psf_e1_residual_histogram(self):
        # general plotter for histograms
        # TODO think about a smart way to define the bin numbers, also
        # make this more general for all quantities
        print('plotting psf e1 residual histogram')
        import matplotlib.pyplot as plt
        bins = 50
        edges = np.linspace(-10, 10, bins+1)
        mids = 0.5*(edges[1:] + edges[:-1])
        calc1 = ParallelStatsCalculator(bins)
        while True:
            data = yield

            if data is None:
                break

            b1 = np.digitize((data['measured_e1']-data['model_e1'])/data['measured_e1'], edges) - 1

            for i in range(bins):
                w = np.where(b1==i)
                # Do more things here to establish
                calc1.add_data(i, (data['measured_e1'][w]-data['model_e1'][w])/data['measured_e1'][w])

        count1, mean1, var1 = calc1.collect(self.comm, mode='gather')
        std1 = np.sqrt(var1/count1)
        if self.rank != 0:
            return
        fig = self.open_output('e1_psf_residual_hist', wrapper=True)
        plt.bar(mids, count1, width=edges[1]-edges[0],edgecolor='black',align='center',color='blue')
        plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        plt.xlabel("($e_{1}-e_{1,psf})/e_{1,psf}$")
        plt.ylabel(r'$N_{stars}$')
        plt.ylim(0,1.1*max(count1))
        fig.close() 
Example 22
Project: TXPipe   Author: LSSTDESC   File: psf_diagnostics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_psf_e2_residual_histogram(self):
        # general plotter for histograms
        # TODO think about a smart way to define the bin numbers, also
        # make this more general for all quantities
        print('plotting psf e2 residual histogram')
        import matplotlib.pyplot as plt
        bins = 50
        edges = np.linspace(-10, 10, bins+1)
        mids = 0.5*(edges[1:] + edges[:-1])
        calc1 = ParallelStatsCalculator(bins)
        while True:
            data = yield

            if data is None:
                break

            b1 = np.digitize((data['measured_e2']-data['model_e2'])/data['measured_e2'], edges) - 1

            for i in range(bins):
                w = np.where(b1==i)
                # Do more things here to establish
                calc1.add_data(i, (data['measured_e2'][w]-data['model_e2'][w])/data['measured_e2'][w])

        count1, mean1, var1 = calc1.collect(self.comm, mode='gather')
        std1 = np.sqrt(var1/count1)
        if self.rank != 0:
            return
        fig = self.open_output('e2_psf_residual_hist', wrapper=True)
        plt.bar(mids, count1, width=edges[1]-edges[0],edgecolor='black',align='center',color='blue')
        plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        plt.xlabel("$(e_{2}-e_{2,psf})/e_{2,psf}$")
        plt.ylabel(r'$N_{stars}$')
        plt.ylim(0,1.1*max(count1))
        fig.close() 
Example 23
Project: TXPipe   Author: LSSTDESC   File: psf_diagnostics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_psf_T_residual_histogram(self):
        # general plotter for histograms
        # TODO think about a smart way to define the bin numbers, also
        # make this more general for all quantities
        print('plotting psf T residual histogram')
        import matplotlib.pyplot as plt
        bins = 50
        edges = np.linspace(-.1, .1, bins+1)
        mids = 0.5*(edges[1:] + edges[:-1])
        calc1 = ParallelStatsCalculator(bins)
        while True:
            data = yield

            if data is None:
                break

            b1 = np.digitize((data['measured_T']-data['model_T'])/data['measured_T'], edges) - 1

            for i in range(bins):
                w = np.where(b1==i)
                # Do more things here to establish
                calc1.add_data(i, (data['measured_T'][w]-data['model_T'][w])/data['measured_T'][w])

        count1, mean1, var1 = calc1.collect(self.comm, mode='gather')
        std1 = np.sqrt(var1/count1)
        if self.rank != 0:
            return
        fig = self.open_output('T_psf_residual_hist', wrapper=True)
        plt.bar(mids, count1, width=edges[1]-edges[0],edgecolor='black',align='center',color='blue')
        plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        plt.xlabel("$(T-T_{psf})/T_{psf}$")
        plt.ylabel(r'$N_{stars}$')
        plt.ylim(0,1.1*max(count1))
        fig.close() 
Example 24
Project: TXPipe   Author: LSSTDESC   File: diagnostics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_snr_histogram(self):
        print('plotting snr histogram')
        import matplotlib.pyplot as plt
        bins = 50
        edges = np.logspace(1, 3, bins+1)
        mids = 0.5*(edges[1:] + edges[:-1])
        calc1 = ParallelStatsCalculator(bins)
        
        while True:
            data = yield

            if data is None:
                break
            
            qual_cut = data['source_bin'] !=-1
#            qual_cut |= data['lens_bin'] !=-1

            b1 = np.digitize(data['mcal_s2n'][qual_cut], edges) - 1

            for i in range(bins):
                w = np.where(b1==i)
                # Do more things here to establish
                calc1.add_data(i, data['mcal_s2n'][qual_cut][w])

        count1, mean1, var1 = calc1.collect(self.comm, mode='gather')
        if self.rank != 0:
            return
        std1 = np.sqrt(var1/count1)
        fig = self.open_output('snr_hist', wrapper=True)
        plt.bar(mids, count1, width=edges[1:]-edges[:-1],edgecolor='black',align='center',color='blue')
        plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        plt.xscale('log')
        plt.xlabel("log(snr)")
        plt.ylabel(r'$N_{galaxies}$')
        plt.ylim(0,1.1*max(count1))
        fig.close() 
Example 25
Project: baconian-project   Author: Lukeeeeee   File: plotter.py    MIT License 5 votes vote down vote up
def plot_fig(self, fig_num, col_id, x, y, title, x_label, y_label, label=' ', marker='*'):
        plt.figure(fig_num, figsize=(6, 5))
        plt.title(title)
        plt.xlabel(x_label)
        plt.ylabel(y_label)
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
        plt.tight_layout()

        marker_every = max(int(len(x) / 10), 1)
        if len(np.array(y).shape) > 1:
            new_shape = np.array(y).shape

            res = np.reshape(np.reshape(np.array([y]), newshape=[-1]), newshape=[new_shape[1], new_shape[0]],
                             order='F').tolist()
            res = list(res)
            for i in range(len(res)):
                res_i = res[i]
                plt.subplot(len(res), 1, i + 1)
                plt.title(title + '_' + str(i))
                plt.plot(x, res_i, self.color_list[col_id], label=label + '_' + str(i), marker=marker,
                         markevery=marker_every, markersize=6, linewidth=1)
                col_id += 1
        else:
            plt.plot(x, y, self.color_list[col_id], label=label, marker=marker, markevery=marker_every, markersize=6,
                     linewidth=1)
        plt.legend() 
Example 26
Project: gtopkssgd   Author: hclhkbu   File: communication.py    Apache License 2.0 5 votes vote down vote up
def plot_p2platency():
    def _fit_linear_function(x, y):
        X = np.array(x)
        Y = np.array(y)
        A = np.vstack([X, np.ones(len(X))]).T
        beta, alpha = np.linalg.lstsq(A, Y, rcond=None)[0]
        return alpha, beta
    fig, ax = plt.subplots(figsize=(5,3.8))
    #fig, ax = plt.subplots(figsize=(5,4.2))
    filename = '/media/sf_Shared_Data/tmp/icdcs2019/mgdlogs/mgd140/p2platency.log'

    sizes, comms, errors = read_allreduce_log(filename)
    comms = [c/1000. for c in comms]
    errors = [c/1000. for c in errors]
    alpha, beta = _fit_linear_function(sizes, comms)
    print('alpha: %f, beta: %f' % (alpha, beta))

    ax.errorbar(sizes, comms, errors, label='Measured Point-to-point Communication', fmt='o', linewidth=1)
    ax.plot(sizes, alpha+np.array(sizes)*beta, label=r'Predicted ($\alpha=%.3f, \beta=%f$)'%(alpha, beta), linewidth=1)
    ax.grid(linestyle=':')
        
    plt.xlabel('Size of parameters [bytes]')
    plt.ylabel(r'Communication time [ms]')
    plt.ylim(bottom=0, top=plt.ylim()[1]*1.2)
    plt.legend(ncol=1, loc=2, prop={'size': 10})
    update_fontsize(ax, fontsize=16)
    plt.subplots_adjust(left=0.16, bottom=0.17, top=0.98, right=0.98)
    plt.ticklabel_format(axis='x', style='sci', scilimits=(0,0))
    plt.savefig('%s/%s.pdf' % (OUTPUT_PATH, 'p2pcommtime'))
    plt.show() 
Example 27
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 5 votes vote down vote up
def plot_chain_fluence_relative_error_history(ratio_evolution, fluence_derivative_dict, history_mid_fluence, sampled_index):

	ratio_name_list = ratio_evolution[1]

	sampled_history_fluence = sample_data_with_sample_indexes(sampled_index, history_mid_fluence)

	fig, ax = plt.subplots()
	count = 0
	linestyle = '-'
	for i in range(len(ratio_name_list)):
		if count > 8:
			linestyle = ':'
		ratio_name = ratio_name_list[i]
		fluence_derivative = fluence_derivative_dict[ratio_name]
		sampled_fluence_derivative = sample_data_with_sample_indexes(sampled_index, fluence_derivative)
		relative_error_seq = [x/y for x, y in zip(sampled_fluence_derivative, sampled_history_fluence)]
		plt.plot(sampled_history_fluence, relative_error_seq, linestyle = linestyle, label = ratio_name)
		count +=1
	plt.ylabel('Fluence relative error', fontsize=16)
	plt.grid()
	ax.yaxis.get_offset_text().set_fontsize(16)
	plt.legend(prop={'size': 15})
	plt.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	plt.tick_params(labelsize=15)
	plt.xlabel('Fluence', fontsize=16)
	plt.yscale('log')
	plt.show() 
Example 28
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 5 votes vote down vote up
def plot_chain_fraction_derivative_history(fraction_derivative_dict, history_mid_fluence):

	fig, ax = plt.subplots()
	for name in fraction_derivative_dict:
		fraction_derivative = fraction_derivative_dict[name]
		plt.plot(history_mid_fluence, fraction_derivative, label = name)
	plt.ylabel('Fraction derivative', fontsize=16)
	plt.grid()
	ax.yaxis.get_offset_text().set_fontsize(16)
	plt.legend(prop={'size': 15})
	plt.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	plt.tick_params(labelsize=15)
	plt.xlabel('Fluence', fontsize=16)
	plt.show() 
Example 29
Project: pymech   Author: jellespijker   File: Axle.py    MIT License 5 votes vote down vote up
def plotfmt(self, figsize=(10, 5)):
        pl.figure(figsize=figsize)
        pl.subplot(311)
        pl.plot(self.properties.geometry.axle, self.V)
        pl.grid(True)
        pl.title('Vertical shear')
        pl.ylabel('Force in [N]')
        pl.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

        pl.subplot(312)
        pl.plot(self.properties.geometry.axle, self.M)
        pl.grid(True)
        pl.title('Bending moments')
        pl.ylabel('Moment in [Nm]')
        pl.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

        pl.subplot(313)
        pl.plot(self.properties.geometry.axle, self.T)
        pl.grid(True)
        pl.title('Torque')
        pl.ylabel('Torque in [Nm]')
        pl.xlabel('Length in [mm]')
        pl.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

        pl.tight_layout()
        pl.show() 
Example 30
Project: alphacsc   Author: alphacsc   File: plot_output.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_convergence_curve(data, info, dirname):
    # plot the convergence curve
    eps = 1e-6

    # compute the best pobj over all methods
    best_pobj = np.min([np.min(r['pobj']) for _, r in data])

    fig = plt.figure("convergence", figsize=(12, 12))
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    color_cycle = itertools.cycle(COLORS)
    for (args, res), color in zip(data, color_cycle):
        times = list(np.cumsum(res['times']))
        plt.loglog(
            times, (res['pobj'] - best_pobj) / best_pobj + eps, '.-',
            label=get_label(info['grid_key'], args), color=color,
            linewidth=2)
    plt.xlabel('Time (s)', fontsize=24)
    plt.ylabel('Objective value', fontsize=24)
    ncol = int(np.ceil(len(data) / 10))
    plt.legend(ncol=ncol, fontsize=24)

    plt.gca().tick_params(axis='x', which='both', bottom=False, top=False)
    plt.gca().tick_params(axis='y', which='both', left=False, right=False)
    plt.tight_layout()
    plt.grid(True)
    figname = "{}/convergence.png".format(dirname)
    fig.savefig(figname, dpi=150) 
Example 31
Project: treetime   Author: neherlab   File: wrappers.py    MIT License 5 votes vote down vote up
def print_save_plot_skyline(tt, n_std=2.0, screen=True, save='', plot=''):
    if plot:
        import matplotlib.pyplot as plt

    skyline, conf = tt.merger_model.skyline_inferred(gen=50, confidence=n_std)
    if save: fh = open(save, 'w')
    header1 = "Skyline assuming 50 gen/year and approximate confidence bounds (+/- %f standard deviations of the LH)\n"%n_std
    header2 = "date \tN_e \tlower \tupper"
    if screen: print('\t'+header1+'\t'+header2)
    if save: fh.write("#"+ header1+'#'+header2+'\n')
    for (x,y, y1, y2) in zip(skyline.x, skyline.y, conf[0], conf[1]):
        if screen: print("\t%1.1f\t%1.1f\t%1.1f\t%1.1f"%(x,y, y1, y2))
        if save: fh.write("%1.1f\t%1.1f\t%1.1f\t%1.1f\n"%(x,y, y1, y2))

    if save:
        print("\n --- written skyline to %s\n"%save)
        fh.close()

    if plot:
        plt.figure()
        plt.fill_between(skyline.x, conf[0], conf[1], color=(0.8, 0.8, 0.8))
        plt.plot(skyline.x, skyline.y, label='maximum likelihood skyline')
        plt.yscale('log')
        plt.legend()
        plt.ticklabel_format(axis='x',useOffset=False)
        plt.savefig(plot) 
Example 32
Project: BPG   Author: BerkeleyPhotonicsGenerator   File: WaveguideAnalysis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_data(self):
        plt.ticklabel_format(axis='both', style='sci', scilimits=(-2, 2))
        x_raw, z_raw = np.squeeze(self.raw_data['x']), np.squeeze(self.raw_data['z'])
        X, Z = np.meshgrid(x_raw, z_raw, indexing='ij')
        plt.contour(X, Z, np.abs(self.raw_data['Ex']))
        plt.grid(True)
        plt.title('Ex')
        plt.xlabel('X')
        plt.ylabel('Z')
        plt.show() 
Example 33
Project: BPG   Author: BerkeleyPhotonicsGenerator   File: WaveguideAnalysis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_data(self):
        plt.ticklabel_format(axis='both', style='sci', scilimits=(-2, 2))
        x_raw, z_raw = np.squeeze(self.data['x']), np.squeeze(self.data['z'])
        X, Z = np.meshgrid(x_raw, z_raw, indexing='ij')
        plt.contour(X, Z, np.abs(self.data['Ex']))
        plt.grid(True)
        plt.title('Ex')
        plt.xlabel('X')
        plt.ylabel('Z')
        plt.show() 
Example 34
Project: TF_RL   Author: Rowing0914   File: plot_comet.py    MIT License 4 votes vote down vote up
def plot(**kwargs):
    labels = kwargs.get('labels')
    data = kwargs.get('data')

    # Setup figure
    fig = plt.figure(figsize=(12, 8))
    ax = plt.subplot()
    for label in (ax.get_xticklabels()):
        label.set_fontname('Arial')
        label.set_fontsize(28)
    for label in (ax.get_yticklabels()):
        label.set_fontname('Arial')
        label.set_fontsize(28)
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    ax.xaxis.get_offset_text().set_fontsize(20)
    axis_font = {'fontname': 'Arial', 'size': '32'}
    colors = sns.color_palette('colorblind', n_colors=len(data))

    # Plot data
    for runs, label, color in zip(data, labels.get('experiments'), colors):
        unique_x_values = set()
        for run in runs:
            for key in run.keys():
                unique_x_values.add(key)
        x_values = sorted(unique_x_values)

        # Plot mean and standard deviation of all runs
        y_values_mean = []
        y_values_std = []

        for x in x_values:
            y_values_mean.append(mean([run.get(x) for run in runs if run.get(x)]))
            y_values_std.append(np.std([run.get(x) for run in runs if run.get(x)]))

        # Plot std
        ax.fill_between(x_values, np.add(np.array(y_values_mean), np.array(y_values_std)),
                        np.subtract(np.array(y_values_mean), np.array(y_values_std)),
                        alpha=0.3,
                        edgecolor=color, facecolor=color)
        # Plot mean
        plt.plot(x_values, y_values_mean, color=color, linewidth=1.5, label=label)

    # Label figure
    ax.legend(loc='lower right', prop={'size': 26})
    ax.set_xlabel(labels.get('x_label'), **axis_font)
    ax.set_ylabel(labels.get('y_label'), **axis_font)
    fig.subplots_adjust(bottom=0.2)
    fig.subplots_adjust(left=0.2)
    ax.set_title(labels.get('title'), **axis_font)

    fig.savefig('../install/{}.pdf'.format(labels.get('title')))

    return 
Example 35
Project: spinningup   Author: openai   File: plot.py    MIT License 4 votes vote down vote up
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    sns.set(style="darkgrid", font_scale=1.5)
    sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', **kwargs)
    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with:

        sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)

    Changes the colorscheme and the default legend style, though.
    """
    plt.legend(loc='best').set_draggable(True)

    """
    For the version of the legend used in the Spinning Up benchmarking page, 
    swap L38 with:

    plt.legend(loc='upper center', ncol=6, handlelength=1,
               mode="expand", borderaxespad=0., prop={'size': 13})
    """

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    plt.tight_layout(pad=0.5) 
Example 36
Project: open-recipe   Author: dspray95   File: _tqdm_gui.py    The Unlicense 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        warn('GUI is experimental/alpha', TqdmExperimentalWarning)
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax 
Example 37
Project: trading-bitcoin-with-reinforcement-learning   Author: ThirstyScholar   File: main.py    MIT License 4 votes vote down vote up
def plot_result(rwd_lst, open_price, close_price):
    plt.subplot(211)

    # Baseline1: BnH
    ret = np.log(close_price / close_price.shift(1))
    ret.fillna(0, inplace=True)

    bnh = np.cumsum(ret.values) * 2
    plt.plot(bnh, label='BnH')

    # Baseline2: Momentum
    log_ret = np.log(close_price / open_price)

    sma = close_price.rolling(30, min_periods=1).mean()
    signal = (close_price > sma).shift(1).astype(float) * 4  # shift by 1 since we trade on the next opening price
    signal.fillna(0, inplace=True)

    mmt = np.cumsum(log_ret.values * signal.values)  # convert to cum. simple return
    plt.plot(mmt, label='MMT')

    # RL agent performance
    rl = np.cumsum(rwd_lst)

    plt.xticks(())
    plt.ylabel('Cumulative Log-Returns')
    plt.plot(rl, label='RL')
    plt.legend()

    def mdd(x):
        max_val = None
        temp = []
        for t in x:
            if max_val is None or t > max_val:
                max_val = t
            temp.append(t - max_val)
        return temp

    plt.subplot(212)
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.xlabel('Timesteps')
    plt.ylabel('MDD')
    plt.plot(mdd(bnh))
    plt.plot(mdd(mmt))
    plt.plot(mdd(rl))
    plt.show() 
Example 38
Project: analyzePF   Author: analyzeDFIR   File: _tqdm_gui.py    MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        self.fp.write('Warning: GUI is experimental/alpha\n')
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax 
Example 39
Project: fast15-paper-extras   Author: zdvresearch   File: analyze_NEW_CATEGORIES_SIZE_JSON_DATA.py    MIT License 4 votes vote down vote up
def plot_percentagereq_for_differen_sizes_forasinglemonth(gray_scale_r, variable_r, width_r, list_of_ranges_r, outplotfile, y_label):

    x_axis_new = []
    for i in range(0, len(list_of_ranges_r)):
        x_axis_new.append(i+1)
    plt.figure(figsize=(list_of_ranges_r.__len__(), 11))
    plt.xticks(x_axis_new, list_of_ranges_r, rotation=70)
    plt.yticks(fontsize=12)
    plt.grid(True)

    temp_list = []

    for ciao in range(0, len(list_of_ranges_r), 1):
        temp_list.append(variable_r[ciao][0])  # change second index to change the month: 0,1,2,...23

    total_requests_in_this_month = float(sum(temp_list))

    print("max of counts %d" % max(temp_list))
    maxim = float(max(temp_list))

    new_list_normalized = []
    #for zeta in range(0, len(list_of_ranges_r), 1):
    for zeta in temp_list:
        new_list_normalized.append(float(zeta/total_requests_in_this_month)*100)

    #print(temp_list)
    #print(new_list_normalized)

    plt.ylim([0, 100])
    #total_get_requests_for_given_month
    for babbo in range(0, len(list_of_ranges_r), 1):
    #    plt.bar(x_axis_new[babbo], variable_r[babbo][0], width_r, color=gray_scale_r[babbo], label=list_of_ranges_r[babbo])

        plt.bar(x_axis_new[babbo], new_list_normalized[babbo], width_r, color=gray_scale_r[babbo], label=list_of_ranges_r[babbo])



    #plt.legend(loc='upper left', fontsize=11)
    #plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    #plt.ylabel('# GET operations ($\cdot 10^6$)', fontsize=20)
    plt.ylabel(y_label, fontsize=15)
    plt.subplots_adjust(bottom=.20)
    #plt.show()

    plt.savefig(outplotfile)
    plt.close()


#def plot_bigplot_getplusput_tape_and_disk(gray_scale_r, x_axis_r, variable_r_get, variable_r_put, width_r, tags_r, list_of_ranges_r, outplotfilename, legend_labels, y_lab):   ##### tape and disk comparison for get and put... bytes and # requests
#    pass 
Example 40
Project: deskOrg   Author: saleguas   File: _tqdm_gui.py    MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        warn('GUI is experimental/alpha', TqdmExperimentalWarning)
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax 
Example 41
Project: TXPipe   Author: LSSTDESC   File: diagnostics.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_g_histogram(self):
        print('plotting histogram')
        import matplotlib.pyplot as plt
        from scipy import stats
        bins = 50
        edges = np.linspace(-1, 1, bins+1)
        mids = 0.5*(edges[1:] + edges[:-1])
        calc1 = ParallelStatsCalculator(bins)
        calc2 = ParallelStatsCalculator(bins)
        
        
        while True:
            data = yield

            if data is None:
                break
            qual_cut = data['source_bin'] !=-1
#            qual_cut |= data['lens_bin'] !=-1
        
            b1 = np.digitize(data['mcal_g1'][qual_cut], edges) - 1

            for i in range(bins):
                w = np.where(b1==i)
                # Do more things here to establish
                calc1.add_data(i, data['mcal_g1'][qual_cut][w])
                calc2.add_data(i, data['mcal_g2'][qual_cut][w])

        count1, mean1, var1 = calc1.collect(self.comm, mode='gather')
        count2, mean2, var2 = calc2.collect(self.comm, mode='gather')
        if self.rank != 0:
            return
        std1 = np.sqrt(var1/count1)
        std2 = np.sqrt(var2/count2)
        fig = self.open_output('g1_hist', wrapper=True)
        plt.bar(mids, count1, width=edges[1]-edges[0],edgecolor='black',align='center',color='blue')
        plt.xlabel("g1")
        plt.ylabel(r'$N_{galaxies}$')
        plt.ylim(0,1.1*max(count1))
        fig.close()

        fig = self.open_output('g2_hist', wrapper=True)
        plt.bar(mids, count2, width=edges[1]-edges[0], align='center',edgecolor='black',color='purple')
        plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
        plt.xlabel("g2")
        plt.ylabel(r'$N_{galaxies}$')
        plt.ylim(0,1.1*max(count2))
        fig.close() 
Example 42
Project: spinningup-drl-prototyping   Author: watchernyu   File: plot.py    MIT License 4 votes vote down vote up
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, no_legend=False,
              legend_loc='best', color=None, font_scale=1.5,
              label_font_size=24, xlabel=None, ylabel=None,
              **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    sns.set(style="darkgrid", font_scale=font_scale)
    # sns.set_palette('bright')

    print("##############")

    ## TODO CHANGE BACK
    sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, legend=(not no_legend), ci='sd', n_boot=0, color=color)
    xlabel = 'environment interactions' if xlabel is None else xlabel
    ylabel = 'average test return' if ylabel is None else ylabel
    plt.xlabel(xlabel, fontsize=label_font_size)
    plt.ylabel(ylabel, fontsize=label_font_size)

    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with:

        sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)

    Changes the colorscheme and the default legend style, though.
    """
    if not no_legend:
        plt.legend(loc=legend_loc, fontsize=label_font_size).draggable()

    """
    For the version of the legend used in the Spinning Up benchmarking page, 
    swap L38 with:

    plt.legend(loc='upper center', ncol=6, handlelength=1,
               mode="expand", borderaxespad=0., prop={'size': 13})
    """

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    plt.tight_layout(pad=0.5) 
Example 43
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 4 votes vote down vote up
def plot_fluence_relative_error_with_ratio_history(ratio_evolution, fluence_derivative_dict, history_mid_fluence, sampled_index, chain, history_matrix, history_fluence, ratio_uncertainty):

	#ratio_evoluton_dict = ratio_evolution[0]
	ratio_name_list = ratio_evolution[1]
	ratio_evolution_dict = ratio_evolution[0]
	nuclide_list = get_nuclide_list_from_chain(chain)
	sampled_history_fluence = sample_data_with_sample_indexes(sampled_index, history_mid_fluence)

	fig, (ax1, ax2) = plt.subplots(2, sharex = True)
	count = 0
	linestyle = '-'
	for i in range(len(ratio_name_list)):
		if count > 8:
			linestyle = ':'
		ratio_name = ratio_name_list[i]
		ratio_evolution = ratio_evolution_dict[ratio_name]
		mid_ratio_evolution = [(x+y)/2 for x,y in zip(ratio_evolution[:-1], ratio_evolution[1:])]
		fluence_derivative = fluence_derivative_dict[ratio_name]

		sampled_mid_ratio_evolution = sample_data_with_sample_indexes(sampled_index, mid_ratio_evolution)
		sampled_fluence_derivative = sample_data_with_sample_indexes(sampled_index, fluence_derivative)
		relative_error_seq = [x*ratio_uncertainty*k/y for x,k, y in zip(sampled_fluence_derivative,sampled_mid_ratio_evolution, sampled_history_fluence)]
		ax1.plot(sampled_history_fluence, relative_error_seq, linestyle = linestyle, label = ratio_name)	

		#relative_error_seq = [x*ratio_uncertainty*k/y for x,k, y in zip(fluence_derivative, mid_ratio_evolution, history_fluence)]
		#ax1.plot(history_fluence[:-1], relative_error_seq, linestyle = linestyle, label = ratio_name)
		
		count +=1
	# Threeshold line
	line = [1E-2 for x in range(len(sampled_history_fluence))]
	ax1.plot(sampled_history_fluence, line, 'r', linestyle = '--')

	#line = [1E-2 for x in range(len(history_fluence))]
	#ax1.plot(sampled_history_fluence, line, 'r', linestyle = '--')
	#ax1.plot(history_fluence, line, 'r', linestyle = '--')

	ax1.set_ylabel('Fluence relative error', fontsize=16)
	ax1.grid()
	ax1.yaxis.get_offset_text().set_fontsize(16)
	ax1.legend(prop={'size': 6})
	ax1.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	ax1.tick_params(labelsize=15)
	ax1.set_yscale('log')
	#ax1.set_xscale('log')

	for i in range(len(nuclide_list)):
		ax2.plot(history_fluence, history_matrix[i], label = nuclide_list[i])
	ax2.set_xlabel('Fluence', fontsize=16)
	ax2.set_ylabel('Atomic fraction', fontsize=16)
	ax2.grid()
	ax2.yaxis.get_offset_text().set_fontsize(16)
	ax2.xaxis.get_offset_text().set_fontsize(16)
	ax2.legend(prop={'size': 15})
	ax2.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	ax2.tick_params(labelsize=15)

	plt.show() 
Example 44
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 4 votes vote down vote up
def plot_selected_ratio_history(selected_list, selected_ratio_dict, history_fluence, batch_break_indexes=None):

	ratio_name_list = selected_list
	plt.style.use('dark_background')

	f, ax = plt.subplots()
	for i in range(len(ratio_name_list)):
		ratio_name = ratio_name_list[i]
		ratio = selected_ratio_dict[ratio_name]
		ax.plot(history_fluence, ratio, label = ratio_name)

	#Fluence at each batch break point
	batch_break_fluence = [history_fluence[i] for i in batch_break_indexes]
	#plt.axvline(x=0, linestyle = '--', color ='grey')
	for fluence in batch_break_fluence:
		print (fluence)
		plt.axvline(x=fluence, linestyle = '--', color ='grey')

	#quit()



	# plt.axvspan(batch_break_fluence[0], batch_break_fluence[2], alpha=0.2, color='grey')
	# plt.axvspan(batch_break_fluence[9], batch_break_fluence[12], alpha=0.2, color='grey')


	ax.set_ylabel('Ratio', fontsize=16)
	ax.set_xlabel('Fluence [cm/cm$^{3}$]', fontsize=16)
	ax.yaxis.get_offset_text().set_fontsize(16)
	ax.xaxis.get_offset_text().set_fontsize(16)
	plt.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	ax.grid(color = 'dimgray')
	plt.tick_params(labelsize=15)
	ax.set_ylim(bottom = 0, top=3.1)
	plt.legend(prop={'size': 12})

	# Put these freaking Shutdown dates on the top
	ax3 = ax.twiny()
	ax3.set_xlim(ax.get_xlim())
	ax3.set_xticks(batch_break_fluence)
	ax3.tick_params(labelsize=11)
	ax3.set_xticklabels(['Shutdown\nApril 1994', 'Shutdown\nApril 2005', 'Shutdown\nJuly 2007', 'Shutdown\nOctober 2015', 'Shutdown\nMarch 2018'])

	#ax3.set_ylim(bottom = 0, top=3.1)

	plt.show() 
Example 45
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 4 votes vote down vote up
def plot_mass_pu_cum_prod_against_fluence(mass_pu_prod_history_matrix, concatenate_history_fluence, batch_break_indexes = None):

	Pu_isotopes = d.Pu_isotopes_name

	# Tot mass of Pu
	tot_pu_seq = []

	for i in range(len(mass_pu_prod_history_matrix[0])):
		tot_pu = 0
		for j in range(len(mass_pu_prod_history_matrix)):
			tot_pu += mass_pu_prod_history_matrix[j][i]
		tot_pu_seq.append(tot_pu)

	f, ax1 = plt.subplots()
	# for i in range(len(Pu_isotopes)):
	# 	ax.plot(concatenate_history_fluence, mass_pu_prod_history_matrix[i], label = Pu_isotopes[i])
	
	ax1.plot(concatenate_history_fluence, tot_pu_seq, 'orange')

	# Fluence at each batch break point
	batch_break_fluence = [concatenate_history_fluence[i] for i in batch_break_indexes]
	for fluence in batch_break_fluence:
		plt.axvline(x=fluence, linestyle = '--', color ='k')

	# tot Pu mass at each batch break point
	batch_break_cum_pu = [round(tot_pu_seq[i],1) for i in batch_break_indexes]


	# for i in batch_break_indexes:
	# 	batch_fluence_seq = concatenate_history_fluence[:i]
	# 	batch_tot_pu_line = [round(tot_pu_seq[i],1) for x in range(len(batch_fluence_seq))]
	# 	ax1.plot(batch_fluence_seq,batch_tot_pu_line, linestyle = '--', color ='darkgrey')

	max_fluence = max(concatenate_history_fluence)

	ax1.set_ylabel('Mass [kg]', fontsize=16)
	ax1.set_xlabel('Fluence [neutrons cm$^{-2}$]', fontsize=16)
	ax1.set_xlim(left = 0, right= max_fluence)
	#ax1.set_ylim(bottom = 0,top = 31)
	#ax.yaxis.get_offset_text().set_fontsize(15)
	ax1.set_yticks([0] + batch_break_cum_pu)
	ax1.xaxis.get_offset_text().set_fontsize(15)
	#plt.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	ax1.grid()
	plt.tick_params(labelsize=15)

	# Put these freaking Shutdown dates on the top
	ax3 = ax1.twiny()
	ax3.set_xlim(left = 0, right= max_fluence)
	#ax3.set_xlim(ax1.get_xlim())
	ax3.set_xticks(batch_break_fluence)
	ax3.tick_params(labelsize=11)
	#ax3.set_xticklabels(['Shutdown\nApril 1994', 'Shutdown\nApril 2005', 'Shutdown\nJuly 2007', 'Shutdown\nOctober 2015'])

	#plt.legend(prop={'size': 12})
	plt.show() 
Example 46
Project: PyLAT   Author: MaginnGroup   File: fitVisc.py    GNU General Public License v3.0 4 votes vote down vote up
def fitvisc(self,time,visc,stddev,plot, popt2):
        #popt2=[1e-3,1.5e-1,1e2,1e3]
        #popt2=[2e-3,5e-2,2e3,2e2]
        #popt2=[1e-4,1e2]
        foundcutoff = False
        foundstart = False
        start = 1
        while not foundstart and start<len(visc):
            if time[start] > 2000:
                foundstart = True
            else:
                start+=1
        cut = 1
        while not foundcutoff and cut<len(visc):
            if stddev[cut] > 0.4*visc[cut]:
                foundcutoff = True
            else:
                cut += 1
        #cut = len(visc)
        #popt2,pcov2 = optimize.curve_fit(self.doubexp, time[start:cut], visc[start:cut],maxfev=1000000,p0=popt2, sigma=stddev[start:cut])
        popt2,pcov2 = optimize.curve_fit(self.doubexp, time[start:cut], visc[start:cut],maxfev=1000000,p0=popt2, sigma=stddev[start:cut],bounds=(0,[np.inf,1,np.inf,np.inf]))
        
        fit = []
        fit1 = []
        fit2 = []
        for t in time:
            fit.append(self.doubexp(t,*popt2))
            fit1.append(self.doubexp1(t,*popt2))
            fit2.append(self.doubexp2(t,*popt2))
        Value = popt2[0]*popt2[1]*popt2[2]+popt2[0]*(1-popt2[1])*popt2[3]
        #Value = popt2[0]
        
        if plot:
            timep = time/1000000
            from matplotlib import pyplot as plt
            from matplotlib import rcParams
            rcParams.update({'font.size':14})
            print('Viscosity estimate is {}'.format(Value))
            print('A={}, alpha={}, tau1={}, tau2={}'.format(popt2[0],popt2[1],popt2[2],popt2[3]))
            print('Time cutoff is {}'.format(time[cut]))
            plt.ticklabel_format(axis='x', style='sci', scilimits=(0,0))
            plt.plot(timep[:len(visc)],visc,label='Viscosity')
            plt.plot(timep[:len(fit)],fit,label='Double Exponential fit')
            plt.plot(timep[:len(fit1)],fit1,label=r'Contribution of $\tau_1$')
            plt.plot(timep[:len(fit2)],fit2,label=r'Contribution of $\tau_2$')
            plt.axvline(timep[cut])
            plt.ylabel('Viscosity (mPa*s)')
            plt.xlabel('Time (ns)')
            plt.legend()
            plt.show()
        
        return(Value) 
Example 47
Project: lambda-OCRmyPDF   Author: chronograph-pe   File: _tqdm_gui.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        warn('GUI is experimental/alpha', TqdmExperimentalWarning)
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax 
Example 48
Project: firedup   Author: kashif   File: plot.py    MIT License 4 votes vote down vote up
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
    if smooth > 1:
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    sns.set(style="darkgrid", font_scale=1.5)
    sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from
    tsplot to lineplot replacing L29 with:

        sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)

    Changes the colorscheme and the default legend style, though.
    """
    plt.legend(loc='best').set_draggable(True)

    """
    For the version of the legend used in the Spinning Up benchmarking page,
    swap L38 with:

    plt.legend(loc='upper center', ncol=6, handlelength=1,
               mode="expand", borderaxespad=0., prop={'size': 13})
    """

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    plt.tight_layout(pad=0.5) 
Example 49
Project: aop-helpFinder   Author: jecarvaill   File: _tqdm_gui.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        self.fp.write('Warning: GUI is experimental/alpha\n')
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax 
Example 50
Project: FloRL   Author: joeybose   File: plot_comet.py    MIT License 4 votes vote down vote up
def plot(**kwargs):
    labels = kwargs.get('labels')
    data = kwargs.get('data')

    # Setup figure
    fig = plt.figure(figsize=(12, 8))
    ax = plt.subplot()
    for label in (ax.get_xticklabels()):
        label.set_fontname('Arial')
        label.set_fontsize(28)
    for label in (ax.get_yticklabels()):
        label.set_fontname('Arial')
        label.set_fontsize(28)
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    ax.xaxis.get_offset_text().set_fontsize(20)
    axis_font = {'fontname': 'Arial', 'size': '32'}
    colors = sns.color_palette('colorblind', n_colors=len(data))

    # Plot data
    for runs, label, color in zip(data, labels.get('experiments'), colors):
        unique_x_values = set()
        for run in runs:
            for key in run.keys():
                unique_x_values.add(key)
        x_values = sorted(unique_x_values)

        # Plot mean and standard deviation of all runs
        y_values_mean = []
        y_values_std = []

        for x in x_values:
            y_values_mean.append(mean([run.get(x) for run in runs if run.get(x)]))
            y_values_std.append(np.std([run.get(x) for run in runs if run.get(x)]))

        # Plot std
        ax.fill_between(x_values, np.add(np.array(y_values_mean), np.array(y_values_std)),
                        np.subtract(np.array(y_values_mean), np.array(y_values_std)),
                        alpha=0.3,
                        edgecolor=color, facecolor=color)
        # Plot mean
        plt.plot(x_values, y_values_mean, color=color, linewidth=1.5, label=label)

    # Label figure
    ax.legend(loc='lower right', prop={'size': 26})
    ax.set_xlabel(labels.get('x_label'), **axis_font)
    ax.set_ylabel(labels.get('y_label'), **axis_font)
    fig.subplots_adjust(bottom=0.2)
    fig.subplots_adjust(left=0.2)
    ax.set_title(labels.get('title'), **axis_font)

    fig.savefig('../install/{}.pdf'.format(labels.get('title')))

    return