Python matplotlib.pyplot.axhline() Examples

The following are code examples for showing how to use matplotlib.pyplot.axhline(). 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: ortholotree   Author: oxpeter   File: internal.py    GNU General Public License v2.0 6 votes vote down vote up
def rank_scores(homologlist, thresh1=0, thresh2=None, genename=None, outfile=None, showplot=False):
    yvalues = sorted([val[1] for val in homologlist.values()], reverse=True)
    plt.plot(yvalues)
    score_cutoff = thresh1 * max(yvalues)
    sample_cutoff = sum(1 for s in yvalues if s >= thresh1 * max(yvalues))
    plt.axhline( score_cutoff , color='r' )
    if thresh2:
        plt.axhline( thresh2 * max(yvalues) , color='r' )
    plt.axvline( sample_cutoff -1 , color='g' )
    plt.text(sample_cutoff + 1,score_cutoff + 10 , "(%d,%d)" % (sample_cutoff,score_cutoff) )
    plt.xlabel("Gene rank")
    plt.ylabel("Phmmer score")
    plt.title("Ranking of phmmer scores for alignment with %s" % genename)
    if outfile:
        plt.savefig(outfile, format='png')
    if showplot:
        plt.show()
    else:
        plt.close() 
Example 2
Project: sthlm-bostad-vis   Author: ashwinvis   File: sssb.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_hist(self, save=True, **kwargs):
        plt.style.use("ggplot")
        self.df_hist.iloc[:, 1:].plot(kind="bar", stacked=True, **kwargs)
        plt.subplots_adjust(left=0.075, bottom=0.4, right=0.83, top=0.95)

        plt.legend(loc="best", fontsize=8, bbox_to_anchor=(1.01, 1.0))
        plt.ylabel("Max. credit days")
        plt.autoscale()

        my_credit_days = (date.today() - self.member_since).days
        plt.axhline(y=my_credit_days)

        if save:
            figname = os.path.join(self.path, self._tag + ".png")
            print("Saving", figname)
            plt.savefig(figname)
        else:
            plt.show() 
Example 3
Project: rldurak   Author: janEbert   File: plot.py    MIT License 6 votes vote down vote up
def main(win_stats, epsilon_start, min_epsilon, epsilon_episodes, count):
    epsilons = np.linspace(epsilon_start, min_epsilon, epsilon_episodes + 1)
    win_stat_count = win_stats.shape[0]
    epsilon_count = epsilons.shape[0]
    if epsilon_count < win_stat_count:
        epsilons = np.append(epsilons, np.full(win_stat_count - epsilon_count,
                min_epsilon))
    win_stat_means = np.mean(win_stats.reshape(-1, count), axis=1)
    epsilon_means = np.mean(epsilons.reshape(-1, count), axis=1)
    episodes = np.arange(count, win_stat_count + 1, count)
    plt.plot(episodes, win_stat_means)
    plt.plot(episodes, epsilon_means)
    plt.axhline(0.5, alpha=0.7, linestyle='dotted', color='grey')
    plt.legend(['Win rate', r'$\epsilon$', '50 %'])
    plt.xlabel('Episodes')
    plt.ylabel('Means of wins over ' + str(count)
            + r' episodes each and $\epsilon$ values')
    plt.title('Win rate during learning')
    plt.savefig(file_name + '.png', bbox_inches='tight')
    plt.savefig(file_name + '.pdf', bbox_inches='tight')
    # plt.show() 
Example 4
Project: morse-code-trainer   Author: partofthething   File: trainer.py    MIT License 6 votes vote down vote up
def plot_history(self):
        """
        Plot training progress as logged
        """
        from matplotlib import pyplot as plt


        times, chars, durations, accuracy = self.read_log()

        transitions = self.get_new_letter_dates(times, chars)

        fig, ax = plt.subplots()
        ax.plot_date(times, accuracy, '-o')
        fig.autofmt_xdate()
        plt.title('Morse Code learning progress')
        plt.ylabel('Accuracy (%)')

        for transition in transitions:
            plt.axvline(x=transition, c='BLACK')

        plt.axhline(y=90, c='RED')

        plt.show() 
Example 5
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 6 votes vote down vote up
def _output_rate(self, frame, plot_class, max_rate, ylabel='Hz'):
		"""
		Minimalistic plot of output firing rate in one dimension
		
		Parameters
		----------
		frame : int
			Sets the time at which the output rate is plotted
		plot_class : class
		input : str
			Sets the ylimit
		Returns
		-------
		"""
		output_rates = plot_class.get_output_rates(frame, spacing=self.spacing,
												   from_file=True)
		plt.plot(self.linspace, output_rates, color='black', lw=1)
		ax = plt.gca()
		general_utils.plotting.simpleaxis(ax)
		ax.set( xticks=[], yticks=[0, max_rate],
				xlabel='', ylabel=ylabel)
		plt.axhline([plot_class.params['out']['target_rate']],
					dashes=(0.7, 0.7),
					color='gray', lw=0.6, zorder=100) 
Example 6
Project: imitation   Author: HumanCompatibleAI   File: train_adversarial.py    MIT License 6 votes vote down vote up
def plot_ep_reward(self):
    """Render and show average episode reward plots."""
    for name in self.gen_ep_reward:
      plt.title(name + " Performance")
      plt.xlabel("epochs")
      plt.ylabel("Average reward per episode (n={})"
                 .format(self.n_episodes_per_reward_data))
      X = self.ep_reward_X
      plt.plot(X, self.gen_ep_reward[name], label="avg gen ep reward", c="red")
      plt.plot(X, self.rand_ep_reward[name],
               label="avg random ep reward", c="black")

      name = name.lower().replace(' ', '-')
      if (self.expert_mean_ep_reward is not None and
              name == "ground-truth-reward"):
          plt.axhline(y=self.expert_mean_ep_reward,
                      linestyle='dashed',
                      label=f"expert (return={self.expert_mean_ep_reward:.2g})",
                      color="black")
      plt.legend()
      self._savefig(f"plot_fight_epreward_gen_{name}", self.show_plots) 
Example 7
Project: PyRSF   Author: martijnende   File: bayes.py    GNU General Public License v3.0 6 votes vote down vote up
def prune_chain(self):
        """
        Sometimes a few walkers get stuck in a local minimum. Prune those
        walkers astray from the sampling chain
        """

        chain = self.chain
        nburn = self.bayes_params["nburn"]

        stats = np.zeros((len(self.inversion_params), 2))

        for i, key in enumerate(self.inversion_params):
            param = chain[:, nburn:, i].reshape(-1)
            std = param.std()
            mean = param.mean()
            dx = np.abs(mean - param)
            param[dx > 2*std] = np.nan
            stats[i, 0] = np.nanmean(param)
            stats[i, 1] = np.nanstd(param)
            plt.plot(np.sort(dx)[::-1], ".")
            plt.axhline(2*std, ls="--", c="k")
            plt.show()

        return stats 
Example 8
Project: data-analysis-pipelines   Author: radujica   File: plot.py    MIT License 6 votes vote down vote up
def plot_profile_scatter_single_cpu(input_, pipelines):
    dfs = {pipeline: read_collectl_pipelines_cpu(input_, pipeline) for pipeline in pipelines}
    dfs['python'] = dfs['python-libraries']
    del dfs['python-libraries']

    max_x = max([df.index.values[-1] for df in dfs.values()])
    [plt.plot(df.index.values, df['cpu_mean'], '-', label=name, color=pipelines_colors[name])
     for name, df in dfs.items()]
    [plt.fill_between(df.index.values, df['cpu_mean'] - df['cpu_diff'], df['cpu_mean'] + df['cpu_diff'], alpha=0.3, facecolor=pipelines_colors[name])
     for name, df in dfs.items()]
    plt.ylabel('CPU (%)', fontsize=12)
    plt.xlabel('Time (s)', fontsize=12)
    plt.title(input_, fontsize=12)
    plt.legend(fontsize=10, labelspacing=0.05, loc='upper right')

    plt.axhline(y=100, color='k', linewidth=0.5)
    plt.text(max_x - 3, 130, '100') 
Example 9
Project: SpaceXtract   Author: shahar603   File: plot_analysed_telemetry.py    MIT License 6 votes vote down vote up
def add_horizontal_lines(data, events, x_key, y_key, rotation=0):
    max_x = max(data[x_key])
    min_x = min(data[x_key])

    ratio_positive = math.fabs(min_x)/(math.fabs(min_x)+math.fabs(max_x))

    for key in events:
        if events[key] is not None:
            if events[key] >= len(data[x_key]):
                continue

            if np.sign(data[x_key][events[key]]) > 0:
                xmin = ratio_positive
                xmax = 1
                x = 0.65*max_x
            else:
                xmin = 0
                xmax = ratio_positive
                x = min_x

            plt.text(x, data[y_key][int(events[key])], events_to_text[key], fontsize=15, rotation=rotation)
            plt.axhline(y=data[y_key][int(events[key])], xmin=xmin, xmax=xmax, color='black', linestyle='--') 
Example 10
Project: Gravity_Simulator   Author: albinjal   File: newton.py    MIT License 6 votes vote down vote up
def save(self, file_name, axis, second):
        plt.axis(axis)
        plt.gca().set_aspect('equal', adjustable='box')
        plt.title('Day: %d, Hour: %d' % (
        math.floor(second / 60 / 60 / 24), second / 60 / 60 - math.floor(second / 60 / 60 / 24) * 24))
        plt.xlabel('Meters')
        plt.ylabel('Meters')
        plt.axvline(color='black')
        plt.axhline(color='black')
        for body in self.bodies:
            print(body.disp())
            plt.scatter(body.position[0], body.position[1], body.diameter/10**5, edgecolors='none')
            if vector_length(body.applied_force) and vector_length(body.velocity):
                plt.quiver(body.position[0], body.position[1], body.applied_force[0], body.applied_force[1],
                           color=['r'], scale=3 * 10 ** 21)
                plt.quiver(body.position[0], body.position[1], body.velocity[0], body.velocity[1], color=['b'],
                           scale=10000)
        plt.savefig(file_name, bbox_inches='tight')
        plt.clf()
        return file_name 
Example 11
Project: chancecons   Author: anqif   File: constraint.py    Apache License 2.0 6 votes vote down vote up
def plot_cdf(self, save_fig = None, *args, **kwargs):
		margins = self.margins()
		if any(margin is None for margin in margins):
			raise Exception("One or more margins is None.")
		margin_vec = [margin.flatten("C") for margin in margins]
		margin_vec = np.concatenate(margin_vec)
		
		x = np.sort(margin_vec)
		y = np.arange(x.size)/float(x.size)
		plt.plot(x, y, *args, **kwargs)
		plt.axvline(0, color = 'grey', linestyle = ':', linewidth = 1.0)

		# Trace fraction horizontally to curve, then vertically to x-intercept.
		# plt.axhline(self.fraction, linestyle = '--')
		idx = np.argmin(np.abs(y - self.fraction))
		plt.plot(x[:(idx + 1)], np.full(idx + 1, self.fraction), color = 'grey', linestyle = '--')
		plt.plot(np.full(idx + 1, x[idx]), y[:(idx + 1)], color = 'grey', linestyle = '--')
		
		plt.ylim(0, 1)
		plt.xlim(x[0], x[-1])
		if save_fig is not None:
			plt.savefig(save_fig, bbox_inches = "tight", pad_inches = 0)
		plt.show() 
Example 12
Project: NICERsoft   Author: paulray   File: plotutils.py    MIT License 6 votes vote down vote up
def plot_cor(mktable, gtitable):
    time, cor, cc = convert_to_elapsed_goodtime(mktable['TIME'], mktable['COR_SAX'], gtitable)
    #time, lon, cc2 = convert_to_elapsed_goodtime(mktable['TIME'], mktable['SAT_LON'], gtitable)

    colornames, cmap, norm = gti_colormap()

    plot.scatter(time, cor, c=np.fmod(cc,len(colornames)), norm=norm,
        cmap=cmap, marker='^', label='COR_SAX')
    #plot.scatter(time, lon, c = colors, cmap = cmap, marker = '_', label = 'Longitude')
    plot.legend(loc = 2)
    plot.ylim((0.0,20.0))
    plot.axhline(5.0,linestyle='--',color='r')
    plot.xlabel('Elapsed Time (s)', labelpad = 1)
    plot.grid(True)
    plot.ylabel('GeV')
    return

#-------------------------THIS PLOTS USEFUL TEXT AT THE TOP OF THE SUPLOT-------
# def calc_nresets(etable, IDS): 
Example 13
Project: skoleni-python-knihovny   Author: tomasbedrich   File: grafy.py    Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def vykresli_spojnice(hodnoty, nadpis, jednotky):
    fig, ax = pyplot.subplots()

    pyplot.title(nadpis)
    pyplot.xlabel('datum')
    pyplot.ylabel(jednotky)

    x_hodnoty = [polozka[0] for polozka in hodnoty]
    y_hodnoty = [polozka[1] for polozka in hodnoty]

    pyplot.plot_date(x_hodnoty, y_hodnoty, 'b-', linewidth=0.5)
    pyplot.axhline(0, linewidth=0.2)

    # v jakých intervalech a jak mají vypadat popisky na ose X
    ax.xaxis.set_major_locator(YearLocator())

    pyplot.show() 
Example 14
Project: random_data   Author: emd   File: sampling.py    GNU General Public License v2.0 6 votes vote down vote up
def plotSummedCrossPhaseError(self):
        '''Plot cross-phase error (summed over frequency) and its fit
        as a function of `self.shifts`.

        '''
        plt.figure()

        # Summed error and fit
        plt.plot(self.shifts, self.E, 'o')
        plt.plot(self.shifts, (self.Efit[0] * self.shifts) + self.Efit[1])

        # Place crosshair at fit's zero crossing, which indicates
        # the trigger offset giving minimal summed error
        plt.axhline(0, c='k')
        plt.axvline(self.tau * self.Fs, c='k')

        plt.xlabel('shift')
        plt.ylabel('summed error, E')

        plt.tight_layout()
        plt.show()

        return 
Example 15
Project: dave   Author: barentsen   File: test_fbls3.py    MIT License 6 votes vote down vote up
def test_blsStrength():

    size = 100
    width = 10
    depth = 1
    y = np.zeros(size)
    counts = np.ones(size)

    y[40:40+width] -= depth

    bls = fbls.computeBlsForOnePeriod(y, counts, width, 1)

    expectedBls = (depth*width) / (np.sqrt(width))

    assert( np.fabs( np.max(bls) - expectedBls) < .01*expectedBls)
    mp.plot(bls, 'ko')
    mp.axhline(expectedBls, color='r') 
Example 16
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 5 votes vote down vote up
def _plot_initial_windows(self, unsig_base_means, unsig_fcs,
                              sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_windows_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_HexBin_plot")
        plt.savefig("{}/Initial_windows_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 17
Project: PEAKachu   Author: tbischler   File: adaptive.py    ISC License 5 votes vote down vote up
def _plot_initial_peaks(self, unsig_base_means, unsig_fcs,
                            sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_peaks_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_peaks_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_peaks_HexBin_plot")
        plt.savefig("{}/Initial_peaks_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 18
Project: deep-learning-note   Author: wdxtub   File: 4_simulate_sin.py    MIT License 5 votes vote down vote up
def draw_correct_line():
    x = np.arange(0, 2 * np.pi, 0.01)
    x = x.reshape((len(x), 1))
    y = np.sin(x)

    pylab.plot(x, y, label='标准 sin 曲线')
    plt.axhline(linewidth=1, color='r')


# 返回训练样本 
Example 19
Project: euclid   Author: njpayne   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_residual_vs_fit(y_act, y_pred, r_value, name):

    #make a scatterplot
    plt.figure()
    plt.scatter(y_pred, y_act - y_pred)
    plt.xlabel("Fitted Value")
    plt.ylabel("Residual")
    plt.text(x = 25, y = 45, s = "R^2: %.3f" % r_value)
    plt.title("Residuals " + name)
    plt.axhline(0, color= 'b', linestyle='-')
    pylab.savefig(os.path.join(os.getcwd(),"Results","Residual Plots",name))

    plt.close()

    return 
Example 20
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_bar_stacked_sisre(fid, field_dfs, extra_row_names, figure_dir):
    """Generate stacked bar plot with SISRE RMS over all satellites (constellation)

    Args:
       fid (_io.TextIOWrapper): File object.
       field_dfs (dict):        Dictionary with SISRE and orbit-only SISRE dataframe.
       extra_row_names (list):  List of extra rows removed from the dataframe.
       figure_dir (PosixPath):  Figure directory.
    """

    figure_path_threshold = figure_dir / f"plot_bar_stacked_sisre_extra_rows_threshold.{FIGURE_FORMAT}"
    figure_path = figure_dir / f"plot_bar_stacked_sisre_extra_rows.{FIGURE_FORMAT}"

    # Define SISRE thresholds
    sisre_threshold = (AxhlineConfig("E", 2, "red"),)  # TODO: Handling of several GNSS

    # Remove satellite rows
    df_sisre_extra = field_dfs["sisre"].drop(set(field_dfs["sisre"].index) - set(extra_row_names))
    df_sisre_orb_extra = field_dfs["sisre_orb"].drop(set(field_dfs["sisre_orb"].index) - set(extra_row_names))

    # Stacked bar plot WITHOUT threshold
    _plot_bar_stacked(fid, df_sisre_extra, df_sisre_orb_extra, figure_path=figure_path, xticks_rotation=20)

    fid.write(
        f"![Blue bars indicate orbit-only SISRE RMS, orange bars clock-only SISRE RMS and green bars 95th percentile SISRE for the used time processing period and over all satellites.]({figure_path})\n\n"
    )

    # Stacked bar plot WITH threshold
    _plot_bar_stacked(
        fid,
        df_sisre_extra,
        df_sisre_orb_extra,
        figure_path=figure_path_threshold,
        xticks_rotation=20,
        axhline=sisre_threshold,
    )

    fid.write(
        f"![Blue bars indicate orbit-only SISRE RMS, orange bars clock-only SISRE RMS and green bars 95th percentile SISRE for the used time processing period and over all satellites. The threshold lines indicate the minimum performance level of the used GNSS.]({figure_path_threshold})\n"
    )
    fid.write("\n\\clearpage\n\n") 
Example 21
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_bar_stacked_sisre_satellites(fid, field_dfs, extra_row_names, figure_dir):
    """Generate stacked bar plot with SISRE RMS for each satellite

    Args:
       fid (_io.TextIOWrapper): File object.
       field_dfs (dict):        Dictionary with SISRE and orbit-only SISRE dataframe.
       extra_row_names (list):  List of extra rows removed from the dataframe.
       figure_dir (PosixPath):  Figure directory.
    """
    figure_path = figure_dir / f"plot_bar_stacked_sisre.{FIGURE_FORMAT}"
    figure_path_threshold = figure_dir / f"plot_bar_stacked_sisre_threshold.{FIGURE_FORMAT}"

    # Define SISRE thresholds
    sisre_threshold = (AxhlineConfig("E", 2, "red"),)  # TODO: Handling of several GNSS

    # Remove extra rows
    df_sisre = field_dfs["sisre"].drop(extra_row_names)
    df_sisre_orb = field_dfs["sisre_orb"].drop(extra_row_names)

    # Stacked bar plot WITHOUT threshold
    _plot_bar_stacked(fid, df_sisre, df_sisre_orb, figure_path=figure_path, xlabel="Satellite")

    fid.write(
        f"![Blue bars indicate orbit-only SISRE RMS, orange bars clock-only SISRE RMS and green bars 95th percentile SISRE for the used time processing period and each satellite.]({figure_path})\n\n"
    )

    # Stacked bar plot WITH threshold
    _plot_bar_stacked(
        fid, df_sisre, df_sisre_orb, figure_path=figure_path_threshold, xlabel="Satellite", axhline=sisre_threshold
    )

    fid.write(
        f"![Blue bars indicate orbit-only SISRE RMS, orange bars clock-only SISRE RMS and green bars 95th percentile SISRE for the used time processing period and each satellite. The threshold lines indicate the minimum performance level of the used GNSS.]({figure_path_threshold})\n"
    )
    fid.write("\n\\clearpage\n\n")


#
# HISTOGRAM PLOTS
# 
Example 22
Project: pohmm-keystroke   Author: vmonaco   File: plotting.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_penalty_example(penalty):
    """
    Show the penalty function for genuine and impostor users
    """
    genuine_idx = penalty['reference_user'] == penalty['query_user']
    genuine = penalty[genuine_idx]
    impostor = penalty[~genuine_idx]
    thresh = genuine['penalty'].max()
    impostor.loc[:, 'type'] = 'Impostor'

    sns.set(style='darkgrid')
    sns.set_context('notebook', font_scale=3.0)
    plt.figure(figsize=(16, 10))

    g = sns.tsplot(impostor, time='event_idx', unit='reference_user', condition='type', value='penalty',
                   color='cubehelix', ci=95)
    g.set_xlabel('Event')
    g.set_ylabel('Penalty')
    plt.plot(genuine['event_idx'], genuine['penalty'], label='Genuine')
    plt.axhline(thresh, linestyle='--', color='k', label='Threshold')
    plt.legend(title=None, loc='lower right')
    plt.xticks(np.linspace(0, 500, 6))
    return 
Example 23
Project: pohmm-keystroke   Author: vmonaco   File: plotting.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_continuous_identification_example(n_users=3, n_events=10, seed=2015):
    import matplotlib.cm as cm
    from matplotlib import gridspec

    np.random.seed(seed)
    T = n_events * 10
    time = np.random.randint(0, n_events * 10, n_events)
    user = np.random.randint(1, n_users + 1, n_events)
    zero = np.zeros(n_events)

    fig = plt.figure(figsize=(6, 4))
    gs = gridspec.GridSpec(2, 1, height_ratios=[n_users, 1])
    ax0 = plt.subplot(gs[0])

    colors = cm.rainbow(np.linspace(0, 1, n_users))
    for i in range(1, n_users + 1):
        ax0.scatter(time[user == i], user[user == i], color=colors[i - 1])
        ax0.axhline(i, color='k', alpha=0.1)

    ax0.xaxis.set_ticklabels([])
    ax0.set_yticks(np.arange(1, n_users + 1))
    ax0.set_ylabel('User')

    ax1 = plt.subplot(gs[1])
    ax1.axhline(0, color='k', alpha=0.1)
    for i in range(1, n_users + 1):
        ax1.scatter(time[user == i], zero[user == i], color=colors[i - 1])
    ax1.set_yticks([])
    ax1.set_ylabel('Global')
    plt.xlabel('Time')

    plt.tight_layout()
    return 
Example 24
Project: BMSG-GAN   Author: akanimax   File: generate_loss_plots.py    MIT License 5 votes vote down vote up
def plot_loss(*loss_vals, plot_name="Loss plot",
              fig_size=(17, 7), save_path=None,
              legends=("discriminator", "generator")):
    """
    plot the discriminator loss values and save the plot if required
    :param loss_vals: (Variable Arg) numpy array or Sequence like for plotting values
    :param plot_name: Name of the plot
    :param fig_size: size of the generated figure (column_width, row_width)
    :param save_path: path to save the figure
    :param legends: list containing labels for loss plots' legends
                    len(legends) == len(loss_vals)
    :return:
    """
    assert len(loss_vals) == len(legends), "Not enough labels for legends"

    plt.figure(figsize=fig_size).suptitle(plot_name)
    plt.grid(True, which="both")
    plt.ylabel("loss value")
    plt.xlabel("spaced iterations")

    plt.axhline(y=0, color='k')
    plt.axvline(x=0, color='k')

    # plot all the provided loss values in a single plot
    plts = []
    for loss_val in loss_vals:
        plts.append(plt.plot(loss_val)[0])

    plt.legend(plts, legends, loc="upper right", fontsize=16)

    if save_path is not None:
        plt.savefig(save_path) 
Example 25
Project: rldurak   Author: janEbert   File: plot_onlyais.py    MIT License 5 votes vote down vote up
def main(durak_stats, epsilon_start, min_epsilon, epsilon_episodes, count):
    epsilons = np.linspace(epsilon_start, min_epsilon, epsilon_episodes + 1)
    durak_stat_count = durak_stats.shape[0]
    epsilon_count = epsilons.shape[0]
    if epsilon_count < durak_stat_count:
        epsilons = np.append(epsilons, np.full(durak_stat_count
                - epsilon_count, min_epsilon))
    ix_count = max(durak_stats) + 1
    durak_stat_means_list = []
    for ix in range(ix_count):
        durak_stat_means = np.ones(durak_stat_count, dtype=np.float)
        durak_stat_means[np.where(durak_stats == ix)] = 0
        durak_stat_means_list.append(
                np.mean(durak_stat_means.reshape(-1, count), axis=1))
    epsilon_means = np.mean(epsilons.reshape(-1, count), axis=1)
    episodes = np.arange(count, durak_stat_count + 1, count)
    win_rate_strings = []
    for ix in range(ix_count):
        plt.plot(episodes, durak_stat_means_list[ix])
        win_rate_strings.append('Win rate for player {0}'.format(ix))
    plt.plot(episodes, epsilon_means)
    plt.axhline(0.5, alpha=0.7, linestyle='dotted', color='grey')
    plt.legend(win_rate_strings + [r'$\epsilon$', '50 %'])
    plt.xlabel('Episodes')
    plt.ylabel('Means of wins over ' + str(count)
            + r' episodes each and $\epsilon$ values')
    plt.title('Win rate during learning')
    plt.savefig(file_name + '.png', bbox_inches='tight')
    plt.savefig(file_name + '.pdf', bbox_inches='tight')
    # plt.show() 
Example 26
Project: fanalysis   Author: OlivierGarciaDev   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mapping_row(self, num_x_axis, num_y_axis, figsize=None):
        """ Plot the Factor map for rows only
        
        Parameters
        ----------
        num_x_axis : int
            Select the component to plot as x axis.
        
        num_y_axis : int
             Select the component to plot as y axis.
        
        figsize : tuple of integers or None
            Width, height of the figure in inches.
            If not provided, defaults to rc figure.figsize

        Returns
        -------
        None
        """
        plt.figure(figsize=figsize)
        plt.scatter(self.row_coord_[:, num_x_axis - 1],
                    self.row_coord_[:, num_y_axis - 1],
                    marker=".", color="white")
        for i in np.arange(0, self.row_coord_.shape[0]):
            plt.text(self.row_coord_[i, num_x_axis - 1],
                     self.row_coord_[i, num_y_axis - 1],
                     self.row_labels_[i],
                     horizontalalignment="center", verticalalignment="center",
                     color="red")
        plt.title("Factor map for rows")
        plt.xlabel("Dim " + str(num_x_axis) + " ("
                    + str(np.around(self.eig_[1, num_x_axis - 1], 2)) + "%)")
        plt.ylabel("Dim " + str(num_y_axis) + " ("
                    + str(np.around(self.eig_[1, num_y_axis - 1], 2)) + "%)")
        plt.axvline(x=0, linestyle="--", linewidth=0.5, color="k")
        plt.axhline(y=0, linestyle="--", linewidth=0.5, color="k")
        plt.show() 
Example 27
Project: marine-phage-paper-scripts   Author: nanoporetech   File: cluster_ani.py    Mozilla Public License 2.0 5 votes vote down vote up
def fancy_dendrogram(*args, **kwargs):
    max_d = kwargs.pop('max_d', None)
    if max_d and 'color_threshold' not in kwargs:
        kwargs['color_threshold'] = max_d
    annotate_above = kwargs.pop('annotate_above', 0)

    ddata = sch.dendrogram(*args, **kwargs)

    if not kwargs.get('no_plot', False):
        # plt.title('Hierarchical Clustering Dendrogram (truncated)')
        # plt.xlabel('sample index or (cluster size)')
        # plt.ylabel('distance')
        plt.xticks([])
        plt.yticks([])
        
        for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y > annotate_above:
                plt.plot(x, y, 'o', c=c)
                # plt.annotate("%.3g" % y, (x, y), xytext=(0, -5),
                #              textcoords='offset points',
                #              va='top', ha='center')
        if max_d:
            plt.axhline(y=max_d, c='k')
    ax = plt.gca()
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    return ddata 
Example 28
Project: hrt   Author: tansey   File: sim_predictors_importance.py    MIT License 5 votes vote down vote up
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        plt.xlabel('')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True) 
Example 29
Project: hrt   Author: tansey   File: sim_predictors_order.py    MIT License 5 votes vote down vote up
def results_plot(tpr_vals, fdr_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for t, f, n in zip(tpr_vals, fdr_vals, names):
            rates.extend(t)
            rates.extend(f)
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        plt.xlabel('')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True) 
Example 30
Project: hrt   Author: tansey   File: sim_predictors_agg.py    MIT License 5 votes vote down vote up
def results_plot(tpr_vals, fdr_vals, r2_vals, names, fdr_threshold):
    import pandas as pd
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        plt.figure(figsize=(12,5))
        rates = []
        labels = []
        models = []
        order = np.argsort([np.mean(r) if len(r) > 0 else 1 for r in r2_vals])
        # for t, f, r, n in zip(tpr_vals, fdr_vals, r2_vals, names):
        for idx in order:
            t, f, r, n = tpr_vals[idx], fdr_vals[idx], r2_vals[idx], names[idx]
            # rates.extend(r)
            rates.extend(t)
            rates.extend(f)
            # labels.extend(['$\\mathbf{r^2}$']*len(r))
            labels.extend(['TPR']*len(t))
            labels.extend(['FDR']*len(f))
            models.extend([n]*(len(t)+len(f)))#+len(r)
        df = pd.DataFrame({'value': rates, 'Rate': labels, 'Model': models})
        df['value'] = df['value'].astype(float)
        ax = sns.boxplot(x='Model', y='value', hue='Rate', data=df)  # RUN PLOT
        plt.xlabel('', fontsize=18, weight='bold')
        # plt.ylabel('Power, FDR, and $\\mathbf{r^2}$', fontsize=18, weight='bold')
        plt.ylabel('Power and FDR', fontsize=18, weight='bold')
        plt.axhline(fdr_threshold, color='red', lw=2, ls='--')
        # ax.tick_params(labelsize=10)
        plt.legend(loc='upper right')
        sns.despine(offset=10, trim=True) 
Example 31
Project: PyFluxPro   Author: OzFlux   File: pfp_cpd.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_slopes(df,d):
    df=df.reset_index(drop=True)
    if d["show_plots"]:
        plt.ion()
    else:
        plt.ioff()
    fig=plt.figure(figsize=(12,8))
    #fig.patch.set_facecolor('white')
    plt.scatter(df['norm_a1_median'],df['norm_a2_median'],s=80,edgecolors='blue',facecolors='none')
    plt.xlim(-4,4)
    plt.ylim(-4,4)
    plt.xlabel('$Median\/normalised\/ a^{1}$',fontsize=16)
    plt.ylabel('$Median\/normalised\/ a^{2}$',fontsize=16)
    plt.title('Normalised slope parameters \n')
    plt.axvline(x=1,color='black',linestyle='dotted')
    plt.axhline(y=0,color='black',linestyle='dotted')
    plot_out_name=os.path.join(d["plot_path"],d['site_name']+"_CPD_slopes.png")
    fig.savefig(plot_out_name)
    if d["show_plots"]:
        plt.draw()
        plt.ioff()
    else:
        plt.ion()
    #if d["call_mode"].lower()!="interactive": plt.close(fig)

#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Quality control within bootstrap 
Example 32
Project: PyFluxPro   Author: OzFlux   File: pfp_rpLL.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_LTparams_ER(ldt,ER,ER_LT,LT_results):
    fig, axs = plt.subplots(3,1,sharex=True,figsize=(24,6))
    axs[0].plot(LT_results["mid_date"],LT_results["rb"],'bo')
    axs[0].set_ylabel("rb (umol/m2/s)")
    axs[1].plot(LT_results["mid_date"],LT_results["E0"],'bo')
    axs[1].set_ylabel("E0 (C)")
    axs[2].plot(ldt,ER,'bo')
    axs[2].plot(ldt,ER_LT,'r--')
    axs[2].axhline(y=0,linewidth=4,color="r")
    axs[2].set_ylabel("ER (umol/m2/s)")
    plt.tight_layout()
    plt.draw() 
Example 33
Project: PyFluxPro   Author: OzFlux   File: pfp_rpLT.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_windows(data_dict, configs_dict, date, noct_flag):

    # Set parameters from dicts
    path = configs_dict['window_plot_output_path']
    window = configs_dict['window_size_days']

    for i in range(2):
        sub_d = subset_daynight(data_dict, noct_flag)
        if noct_flag:
            daynight_ind = 'noct'
            x_lab = r'Temperature ($^{o}C$)'
            x_var = sub_d['TempC']
            y_var1 = sub_d['NEE']
            y_var2 = sub_d['Re']
        else:
            daynight_ind = 'day'
            x_lab = r'PAR ($\mu mol\/photons\/m^{-2}s^{-1}$)'
            x_var = sub_d['PAR']
            y_var1 = sub_d['NEE']
            y_var2 = sub_d['NEE_est']

        # Plot
        date_str = datetime.datetime.strftime(date,'%Y-%m-%d')
        fig = plt.figure(figsize = (13,8))
        fig.patch.set_facecolor('white')
        plt.plot(x_var, y_var1, 'bo' , label = 'NEE_obs')
        plt.plot(x_var, y_var2, 'ro', label = 'NEE_est')
        plt.title('Fit for ' + str(window) + ' day window centred on ' +
                  date_str + '\n', fontsize = 22)
        plt.xlabel(x_lab, fontsize = 16)
        plt.ylabel(r'NEE ($\mu mol C\/m^{-2} s^{-1}$)', fontsize = 16)
        plt.axhline(y = 0, color = 'black')
        plot_out_name = daynight_ind + '_' + date_str + '.jpg'
        plt.tight_layout()
        fig.savefig(os.path.join(path, plot_out_name))
        plt.close(fig)

    return 
Example 34
Project: SparseSC   Author: microsoft   File: example_graphs.py    MIT License 5 votes vote down vote up
def sc_diff(est_ret, treatment_date, unit_idx, treatment_date_fit=None):
    fig, ax = plt.subplots(num="sc_diff")
    if isinstance(est_ret.Y, pd.DataFrame):
        Y_target = est_ret.Y.iloc[unit_idx,:]
        Y_target_sc = est_ret.get_sc(treatment_date).iloc[unit_idx,:]
    else:
        Y_target = est_ret.Y[unit_idx,:]
        Y_target_sc = est_ret.get_sc(treatment_date)[unit_idx,:]

    diff = Y_target - Y_target_sc
    if est_ret.ind_CI is not None:
        ind_ci = est_ret.ind_CI[treatment_date]
        if isinstance(est_ret.Y, pd.DataFrame):
            fb_index = Y_target.index
        else:
            fb_index = range(len(ind_ci.ci_low))
        plt.fill_between(
            fb_index,
            diff + ind_ci.ci_low,
            diff + ind_ci.ci_high,
            facecolor="gray",
            label="CI",
        )
    plt.axhline(y=0, linestyle="--")
    plt.plot(diff, "kx--", label="Unit Diff")
    if treatment_date_fit is not None:
        plt.axvline(x=treatment_date, linestyle="--", label="Treatment")
        plt.axvline(x=treatment_date_fit, linestyle=":", label="End Fit Window")
    else:
        plt.axvline(x=treatment_date, linestyle="--")
    plt.xlabel("Time")
    plt.ylabel("Real-SC Outcome Difference")
    plt.legend(loc=1)
    return fig, ax 
Example 35
Project: SparseSC   Author: microsoft   File: example_graphs.py    MIT License 5 votes vote down vote up
def te_plot(est_ret, treatment_date, treatment_date_fit=None):
    fig, ax = plt.subplots(num="te_plot")
    if isinstance(est_ret.pl_res_pre.effect_vec.effect, pd.Series):
        effect_vec = pd.concat((est_ret.pl_res_pre.effect_vec.effect, 
                                est_ret.pl_res_post.effect_vec.effect))
    else:
        effect_vec = np.concatenate((est_ret.pl_res_pre.effect_vec.effect, 
                                     est_ret.pl_res_post.effect_vec.effect))
    if est_ret.pl_res_pre.effect_vec.ci is not None:
        if isinstance(est_ret.pl_res_pre.effect_vec.ci.ci_low, pd.Series):
            ci0 = pd.concat((est_ret.pl_res_pre.effect_vec.ci.ci_low, 
                             est_ret.pl_res_post.effect_vec.ci.ci_low))
            ci1 = pd.concat((est_ret.pl_res_pre.effect_vec.ci.ci_high,
                             est_ret.pl_res_post.effect_vec.ci.ci_high))
            plt.fill_between(ci0.index, ci0, ci1, facecolor="gray", label="CI")
        else:
            ci0 = np.concatenate((est_ret.pl_res_pre.effect_vec.ci.ci_low, 
                                  est_ret.pl_res_post.effect_vec.ci.ci_low))
            ci1 = np.concatenate((est_ret.pl_res_pre.effect_vec.ci.ci_high,
                                  est_ret.pl_res_post.effect_vec.ci.ci_high))
            plt.fill_between(range(len(ci0)), ci0, ci1, facecolor="gray", label="CI")

    plt.plot(effect_vec, "kx--", label="Treated Diff")
    if treatment_date_fit is not None:
        plt.axvline(x=treatment_date, linestyle="--", label="Treatment")
        plt.axvline(x=treatment_date_fit, linestyle=":", label="End Fit Window")
    else:
        plt.axvline(x=treatment_date, linestyle="--")
    plt.axhline(y=0, linestyle="--")
    plt.xlabel("Time")
    plt.ylabel("Real-SC Outcome Difference")
    plt.legend(loc=1)
    return fig, ax 
Example 36
Project: verb-attributes   Author: uwnlp   File: fig_4.py    MIT License 5 votes vote down vote up
def att_plot(top_labels, gt_ind, probs, fn):
    # plt.figure(figsize=(5, 5))
    #
    # color_dict = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
    # colors = [color_dict[c] for c in
    #           ['lightcoral', 'steelblue', 'forestgreen', 'darkviolet', 'sienna', 'dimgrey',
    #            'darkorange', 'gold']]
    # colors[gt_ind] = color_dict['crimson']
    # w = 0.9
    # plt.bar(np.arange(len(top_labels)), probs, w, color=colors, alpha=.9, label='data')
    # plt.axhline(0, color='black')
    # plt.ylim([0, 1])
    # plt.xticks(np.arange(len(top_labels)), top_labels, fontsize=6)
    # plt.subplots_adjust(bottom=.15)
    # plt.tight_layout()
    # plt.savefig(fn)
    lab = deepcopy(top_labels)
    lab[gt_ind] += ' (gt)'
    d = pd.DataFrame(data={'probs': probs, 'labels':lab})
    fig, ax = plt.subplots(figsize=(4,5))
    ax.tick_params(labelsize=15)

    sns.barplot(y='labels', x='probs', ax=ax, data=d, orient='h', ci=None)
    ax.set(xlim=(0,1))

    for rect, label in zip(ax.patches,lab):
        w = rect.get_width()
        ax.text(w+.02, rect.get_y() + rect.get_height()*4/5, label, ha='left', va='bottom',
                fontsize=25)

    # ax.yaxis.set_label_coords(0.5, 0.5)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.get_xaxis().label.set_visible(False)
    fig.savefig(fn, bbox_inches='tight', transparent=True)
    plt.close('all') 
Example 37
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def output_rate_distribution(self, start_time=0):
        n_bins = 100
        positions = self.positions[:,0][start_time:,]
        output_rates = self.output_rates[start_time:,]
        dx = 2*self.radius / n_bins
        bin_centers = np.linspace(dx, 2*self.radius-dx, num=n_bins)
        mean_output_rates = []
        for i in np.arange(0, n_bins):
            indexing = (positions >= i*dx) & (positions < (i+1)*dx)
            mean_output_rates.append(np.mean(output_rates[indexing]))
        plt.plot(bin_centers, mean_output_rates, marker='o')
        plt.axhline(y=self.target_rate, linewidth=3, linestyle='--', color='black') 
Example 38
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def different_grid_spacings_in_line():
	date_dir = '2015-07-09-16h10m55s_different_grid_spacings'
	tables = get_tables(date_dir=date_dir)
	psps = [p for p in tables.paramspace_pts()]
	plot = plotting.Plot(tables=tables, psps=psps)
	gs = gridspec.GridSpec(2, 4, height_ratios=[1,1])
	for n, psp in enumerate(psps):
		plot.set_params_rawdata_computed(psp, set_sim_params=True)
		plt.subplot(gs[0, n])
		# max_rate = 9 if (input == 'grf') else 5
		if (plot.params['inh']['sigma'] == 0.3 or plot.params['inh']['sigma'] == 4.0):
			end_frame = plot.time2frame(1e5, weight=True)
		else:
			end_frame = -1
		output_rates = plot.get_output_rates(end_frame, spacing=None,
											 from_file=True)
		plt.plot(output_rates, color='gray', lw=2)
		ax = plt.gca()
		general_utils.plotting.simpleaxis(ax)
		ax.spines['left'].set_color('none')
		ax.set(
			xticks=[], yticks=[],
			ylim=[0, 16.5]
		)
		plt.axhline([plot.params['out']['target_rate']],
					dashes=(4, 4),
					color='black', lw=2, zorder=100, label=r'Target rate')
		if n == 0:
			plt.plot(output_rates, color='gray', lw=2, label='Output rate')
			plt.legend(loc='center left', numpoints=1, frameon=False, fontsize=12)
			plt.yticks([0])

	fig = plt.gcf()
	fig.set_size_inches(6, 5)
	gs.tight_layout(fig, rect=[0, 0, 1, 1], pad=0.2) 
Example 39
Project: survival   Author: ryu577   File: compare_survival_approaches.py    MIT License 5 votes vote down vote up
def non_parametric_comparison():
	num_samples = []
	threshs = []
	tru_opt = 0.0
	for filename in os.listdir('./data/'):
		dd = genfromtxt('./data/' + filename)
		samples = dd[1]
		num_samples.append(samples)
		tru_thresh = dd[4]
		non_prm = dd[5]
		threshs.append(non_prm)
		tru_opt = dd[4]
	plt.plot(num_samples, threshs, 'ro')
	num_samples = np.array(num_samples)
	threshs = np.array(threshs)
	stds = []
	means = []
	for i in np.unique(num_samples):
		stds.append(np.std(threshs[num_samples==i]))
		means.append(np.mean(threshs[num_samples==i]))
	means = np.array(means)
	stds = np.array(stds)
	plt.plot(np.unique(num_samples), means, 'k-')
	plt.axhline(tru_opt, color='g')
	plt.fill_between(np.unique(num_samples), means+stds, means-stds)
	plt.xlabel('Number of samples generated')
	plt.ylabel('Optimum threshold values')
	plt.show() 
Example 40
Project: python-holteandtalley   Author: garrettdreyfus   File: test.py    MIT License 5 votes vote down vote up
def profilePlotter(x,y,line,depths,variable,lat,lon,path):
    plt.plot(x,y)
    plt.ylim(500,0)
    plt.axhline(line)
    for i in depths:
        #Make random markers with labels
        plt.plot(x[i[0]],y[i[0]],'ro')
    plt.xlabel("Densities (kg/m^3)")
    plt.ylabel("Pressures (dbar)")
    plt.title(str("lat : "+lat+
                "lon : "+lon+
                "path :  "+path + "  mlt: " + path))
    plt.show() 
Example 41
Project: wtte-rnn   Author: ragulpr   File: weibull_contour.py    MIT License 5 votes vote down vote up
def weibull_contour(Y, U, is_discrete, true_alpha, true_beta, logx=True, samples=200, lines=True):

    xlist = np.linspace(true_alpha / np.e, true_alpha * np.e, samples)
    ylist = np.linspace(true_beta / np.e, true_beta * np.e, samples)
    x_grid, y_grid = np.meshgrid(xlist, ylist)

    loglik = x_grid * 0

    if is_discrete:
        fun = weibull.discrete_loglik
    else:
        fun = weibull.continuous_loglik

    for i in xrange(len(Y)):
        loglik = loglik + \
            fun(Y[i], x_grid, y_grid, U[i])

    z_grid = loglik / len(Y)

    plt.figure()
    if logx:
        x_grid = np.log(x_grid)
        true_alpha = np.log(true_alpha)
        xlab = r'$\log(\alpha)$'
    else:
        xlab = r'$\alpha$'

    cp = plt.contourf(x_grid, y_grid, z_grid, 100, cmap='jet')
    plt.colorbar(cp)
    if lines:
        plt.axvline(true_alpha, linestyle='dashed', c='black')
        plt.axhline(true_beta, linestyle='dashed', c='black')
    plt.xlabel(xlab)
    plt.ylabel(r'$\beta$') 
Example 42
Project: nanopores   Author: mitschabaude   File: pughpoints.py    MIT License 5 votes vote down vote up
def plot_1Dgrid(z, grids):
    totalgrid = list(set(reduce(lambda a, b: a+b, grids)) - set(z))
    fig = plt.figure("line")
    fig.set_size_inches(8, 1)
    plt.axhline(y=0, color="black", zorder=-10)
    plt.scatter(totalgrid, [0.]*len(totalgrid), color="black")
    plt.scatter(z, [0.]*len(z), color="red")
    plt.xlim(z[0]-1, z[-1]+1)
    plt.axis('off') 
Example 43
Project: nanopores   Author: mitschabaude   File: currents-ahem.py    MIT License 5 votes vote down vote up
def plot_grid(color="#aaaaaa"):
    plt.axvline(x=0, color=color, linestyle="-")
    plt.axhline(y=0, color=color, linestyle="-") 
Example 44
Project: vwoptimize   Author: denik   File: plotting.py    MIT License 5 votes vote down vote up
def main_plot_history(trials, bandit=None, algo=None, do_show=True,
                      status_colors=None):
    # -- import here because file-level import is too early
    import matplotlib.pyplot as plt

    # self is an Experiment
    if status_colors is None:
        status_colors = default_status_colors

    # XXX: show the un-finished or error trials
    Ys, colors = zip(*[(y, status_colors[s])
                       for y, s in zip(trials.losses(bandit), trials.statuses(bandit))
                       if y is not None])
    plt.scatter(range(len(Ys)), Ys, c=colors)
    plt.xlabel('time')
    plt.ylabel('loss')

    if bandit is not None and bandit.loss_target is not None:
        plt.axhline(bandit.loss_target)
        ymin = min(np.min(Ys), bandit.loss_target)
        ymax = max(np.max(Ys), bandit.loss_target)
        yrange = ymax - ymin
        ymean = (ymax + ymin) / 2.0
        plt.ylim(
            ymean - 0.53 * yrange,
            ymean + 0.53 * yrange,
        )
    best_err = trials.average_best_error(bandit)
    print("avg best error:", best_err)
    plt.axhline(best_err, c='g')

    plt.title('bandit: %s algo: %s' % (
        bandit.short_str() if bandit else '-',
        algo_as_str(algo)))
    if do_show:
        plt.show() 
Example 45
Project: vwoptimize   Author: denik   File: plotting.py    MIT License 5 votes vote down vote up
def main_show(self, title=None):
            self.add_scatters()
            if title:
                plt.title(title)
            # plt.axvline(25) # make a parameter
            # plt.axhline(.2)
            # plt.axhline(.3)
            plt.show() 
Example 46
Project: vwoptimize   Author: denik   File: plotting.py    MIT License 5 votes vote down vote up
def main_plot_histories(cls):
        import plotting
        conn_str_template = sys.argv[2]
        algos = sys.argv[3].split(',')
        dataset_name = sys.argv[4]
        start = int(sys.argv[5]) if len(sys.argv) > 5 else 0
        stop = int(sys.argv[6]) if len(sys.argv) > 6 else sys.maxint
        mh = plotting.MultiHistory()
        colors = ['r', 'y', 'b', 'g', 'c', 'k']

        def custom_err_fn(trial):
            if 2 == trial['status']:
                rval = 1.0 - trial['result']['best_epoch_valid']
                if rval > dict(
                        convex=.4,
                        mnist_rotated_background_images=2)[dataset_name]:
                    return None
                else:
                    return rval

        for c, algo in zip(colors, algos):
            conn_str = conn_str_template % (algo, dataset_name)
            print('algo', algo)
            mh.add_experiment(
                mj=MongoJobs.new_from_connection_str(conn_str),
                y_fn=custom_err_fn,
                color=c,
                label=algo,
                start=start,
                stop=stop)
        plt = plotting.plt
        # TODO: icml07 undefined
        plt.axhline(
            1.0 - icml07.dbn3_scores[dataset_name],
            c='k', label='manual+grid')  # , dashes=[0,1])
        mh.add_scatters()
        plt.legend()
        plt.title(dataset_name)
        plt.show() 
Example 47
Project: dvb.datascience   Author: devolksbank   File: score.py    MIT License 5 votes vote down vote up
def precision_recall_curve(self):
        if self.n_classes != 2:
            display(
                "Precision-recall-curve not yet implemented for multiclass classifiers"
            )
            return None

        precision_curve, recall_curve, threshold = sklearn.metrics.precision_recall_curve(
            self.y_true, self.y_pred_proba[self.y_pred_proba_labels[1]]
        )
        precision = self._precision()
        average_precision = self._average_precision()
        recall = self._recall()

        fig = plt.figure()
        from matplotlib.colors import rgb2hex

        color_dark = rgb2hex(plt.cm.get_cmap("Blues")(255))
        color_light = rgb2hex(plt.cm.get_cmap("Blues")(50))
        plt.step(recall_curve, precision_curve, where="post", color=color_dark)
        plt.fill_between(recall_curve, precision_curve, step="post", color=color_light)
        plt.xlabel("Recall")
        plt.ylabel("Precision")
        plt.axhline(precision, label="%.2f" % precision, color="r")
        plt.axvline(recall, label="%.2f" % recall, color="b")
        plt.ylim([0.0, 1.05])
        plt.xlim([0.0, 1.0])
        plt.legend()
        plt.title(
            "2-class Precision-Recall curve: AP={0:0.2f}".format(average_precision)
        )

        display(HTML("<h2>Precision Recall Curve</h2>"))
        display(fig)

        return {
            "precision": precision,
            "recall": recall,
            "threshold": threshold,
            "fig": fig,
        } 
Example 48
Project: oggm-edu   Author: OGGM   File: funcs.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def glacier_plot(x, bed, model, mb_model, init_flowline):
    """This function plots the glacier outline of a model. The bedrock, the
    equilibrium line altitude, labeled axes and a legend are added.

    Parameters
    ----------
    x : ndarray
        distance along glacier
    bed : ndarray
        the glacier bed
    model : oggm.core.flowline.FluxBasedModel
        OGGM model class
    mb_model : oggm.core.massbalance.LinearMassBalance
        the glacier mass balance model
    init_flowline : oggm.core.flowline.RectangularBedFlowline
        the glacier flowline

    Returns
    -------
        a labeled glacier plot (x,z)
    """

    # Plot the initial glacier:
    plt.plot(x, init_flowline.surface_h, label='Initial glacier')
    # Get the modelled flowline (model.fls[-1]) and plot its surface
    plt.plot(x, model.fls[-1].surface_h,
             label='Glacier after {} years'.format(model.yr))
    # Plot the equilibrium line altitude
    plt.axhline(mb_model.ela_h, linestyle='--', color='k', linewidth=0.8)
    # Add the bedrock and axes labels:
    plt.plot(x, bed, color='k', label='Bedrock', linestyle=':', linewidth=1.5)
    plt.xlabel('Distance along glacier [km]')
    plt.ylabel('Altitude [m]')
    plt.legend(loc='best') 
Example 49
Project: calplot   Author: magnusjahre   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def plotLines(xvalues, ydataseries, **kwargs):

    ax = setUpFonts(kwargs)

    plt.axhline(0, color='black')

    markEvery = 1
    if "markEvery" in kwargs:
        markEvery = kwargs["markEvery"]

    if "divFactor" in kwargs:
        for i in range(len(ydataseries)):
            for j in range(len(ydataseries[i])):
                if ydataseries[i][j] is not None:
                    ydataseries[i][j] = ydataseries[i][j] / kwargs["divFactor"]

    lines = []
    useMarkers = ['o', 'v', '^', '<', '>', 's', '*', 'D', 'd', 'P', 'X', 'p', '8']
    for i in range(len(ydataseries)):
        thisColor = cm.Paired(1 * (float(i) / float(len(ydataseries))))
        thisMarker = useMarkers[i % len(useMarkers)]
        lines += ax.plot([float(x) for x in xvalues], ydataseries[i], color=thisColor, marker=thisMarker, markevery=markEvery)

    labels = None
    if "titles" in kwargs:
        if len(kwargs["titles"]) != len(ydataseries):
            raise Exception("The titles list must have the same length as the y-datalist list")

        labels = kwargs["titles"]
        for i in range(len(labels)):
            labels[i] = labels[i].replace("_", " ")

        addLegend(ax, lines, labels, kwargs)

    rotation = "horizontal"
    if "rotate" in kwargs:
        rotation = kwargs["rotate"]
    plt.xticks(rotation=rotation)

    addLabelsAndSeparators(ax, kwargs)
    processOutput(kwargs) 
Example 50
Project: RedditScore   Author: crazyfrogspb   File: redditmodel.py    MIT License 5 votes vote down vote up
def fancy_dendrogram(z, labels, **kwargs):
    # Function to plot fancy dendrograms
    # Taken from:
    # https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial/
    max_d = kwargs.pop('max_d', None)
    if max_d and 'color_threshold' not in kwargs:
        kwargs['color_threshold'] = max_d
    annotate_above = kwargs.pop('annotate_above', 0)

    ddata = hac.dendrogram(z, labels=labels, **kwargs)

    if not kwargs.get('no_plot', False):
        plt.title('Hierarchical Clustering Dendrogram')
        plt.xlabel('Class')
        plt.ylabel('Metric')
        for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y > annotate_above:
                plt.plot(x, y, 'o', c=c)
                plt.annotate("%.3g" % y, (x, y), xytext=(0, -5),
                             textcoords='offset points',
                             va='top', ha='center')
        if max_d:
            plt.axhline(y=max_d, c='k')
    return ddata