當前位置: 首頁>>代碼示例>>Python>>正文


Python seaborn.lineplot方法代碼示例

本文整理匯總了Python中seaborn.lineplot方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.lineplot方法的具體用法?Python seaborn.lineplot怎麽用?Python seaborn.lineplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在seaborn的用法示例。


在下文中一共展示了seaborn.lineplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: evolution_over_time

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def evolution_over_time(self, column, **kwargs):
        """
        Visualize the evolution over time of a column for all assets in group.

        Parameters:
            - column: The name of the column to visualize.
            - kwargs: Additional keyword arguments to pass down
                      to the plotting function.

        Returns:
            A matplotlib Axes object.
        """
        if 'ax' not in kwargs:
            fig, ax = plt.subplots(1, 1, figsize=(10, 4))
        else:
            ax = kwargs.pop('ax')
        return sns.lineplot(
            x=self.data.index,
            y=column,
            hue=self.group_by,
            data=self.data,
            ax=ax,
            **kwargs
        ) 
開發者ID:stefmolin,項目名稱:stock-analysis,代碼行數:26,代碼來源:stock_visualizer.py

示例2: analyze

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def analyze():
  action_count = np.load(action_count_dir, allow_pickle=True)
  print('action count loaded')

  # action taken > 0
  count_dict = {}
  for i, v in enumerate(action_count):
    if v > 0:
      count_dict[i] = v

  print('\n\n')
  for k, v in sorted(count_dict.items()):
    print('action: {}, count: {}'.format(k, v))

  # y = np.load(data_dir + '/y_all_3695_score.npy')
  # print(y[:20])

  # plot barplot
  seaborn.lineplot(list(count_dict.keys()), list(count_dict.values()))
  plt.title('Action Count')
  plt.xlabel('Action Index')
  plt.ylabel('Count')
  plt.show() 
開發者ID:shidi1985,項目名稱:L2RPN,代碼行數:25,代碼來源:analyze_action.py

示例3: visualize_distribution_time_serie

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def visualize_distribution_time_serie(ts,value,path=None):
    """
    Visualize the time-serie data in each individual dimensions.

    Parameters
    ----------
    ts: numpy array of shape (n_test, n_features)
        The value of the test time serie data.
    value: numpy array of shape (n_test, )
        The outlier score of the test data.
    path: string
        The saving path for result figures.
    """
    sns.set(style="ticks")

    ts = pd.DatetimeIndex(ts)
    value=value.to_numpy()[:,1:]
    data = pd.DataFrame(value,ts)
    data = data.rolling(2).mean()
    sns_plot=sns.lineplot(data=data, palette="BuGn_r", linewidth=0.5)
    if path:
        sns_plot.figure.savefig(path+'/timeserie.png')
    plt.show() 
開發者ID:datamllab,項目名稱:pyodds,代碼行數:25,代碼來源:plotUtils.py

示例4: plot_data

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def plot_data(data, time="Iteration", value="AverageReturn", combine=False):
    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    plt.figure(figsize=(16, 9))
    sns.set(style="darkgrid", font_scale=1.5)
    if not combine:
        sns.tsplot(data=data, time=time, value=value, unit="Unit", condition="Condition")
    else:
        df1 = data.loc[:, [time, value[0], 'Condition']]
        df1['Statistics'] = value[0]
        df1.rename(columns={value[0]:'Value', 'Condition':'ExpName'}, inplace = True)
        df2 = data.loc[:, [time, value[1], 'Condition']]
        df2['Statistics'] = value[1]
        df2.rename(columns={value[1]:'Value', 'Condition':'ExpName'}, inplace = True)
        data = pd.concat([df1, df2], ignore_index=True)
        sns.lineplot(x=time, y='Value', hue='ExpName', style='Statistics', data=data)
        
    plt.legend(loc='best').draggable()
    plt.savefig('result.png', bbox_inches='tight')
    plt.show() 
開發者ID:KuNyaa,項目名稱:berkeleydeeprlcourse-homework-pytorch,代碼行數:22,代碼來源:plot.py

示例5: plot_mean_var

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def plot_mean_var(ad, title, ax):
    ad = ad.copy()

    sc.pp.filter_cells(ad, min_counts=1)
    sc.pp.filter_genes(ad, min_counts=1)

    m = ad.X.mean(axis=0)
    v = ad.X.var(axis=0)

    coefs, r2 = _fitquad(m, v)

    ax.set(xscale="log", yscale="log")
    ax.plot(m, v, 'o', c='black', markersize=1)

    poly = np.poly1d(coefs)
    sns.lineplot(m, poly(m), ax=ax, color='red')

    ax.set_title(title)
    ax.set_ylabel('Variance')
    ax.set_xlabel(r'$\mu$')

    sns.lineplot(m, m, ax=ax, color='blue')
    ax.legend(['Genes', r'NB ($\theta=%.2f)\ r^2=%.3f$' % (coefs[0], r2), 'Poisson'])

    return coefs[0] 
開發者ID:theislab,項目名稱:dca,代碼行數:27,代碼來源:utils.py

示例6: plot_relative_error

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def plot_relative_error(data_dir="heterogeneous_example_data"):
    if data_dir[-1] != "/":
        data_dir += "/"
    data_filename = data_dir + "heterogeneous_example_error_data.json"
    data = json.load(open(data_filename))

    plotting_data = []
    for n in data.keys():
        for i in data[n].keys():
            d = {"Sample Size": int(n), "Iteration": int(i)}
            true_effects = data[n][str(i)]["true_effects"]
            estimated_effects = data[n][str(i)]["estimated_effects"]
            error = np.array(true_effects) - np.array(estimated_effects)
            relative_error = np.linalg.norm(error) / np.linalg.norm(true_effects)
            d["Relative Error"] = relative_error
            plotting_data.append(d)
    plotting_df = pd.DataFrame(plotting_data)

    plt.figure(figsize=(18, 8))
    ax = plt.gca()
    grid = sns.lineplot(
        x="Sample Size", y="Relative Error", data=plotting_df, marker="o", ax=ax
    )
    sample_sizes = [int(n) for n in data.keys()]
    ax.set_xticks(sample_sizes)
    ax.set_xticklabels([""] + sample_sizes[1:], rotation=45)
    ax.set_xlim([0, max(sample_sizes) + 100])
    sns.despine()
    plt.title("Relative Error of Causal Forest")
    plt.show() 
開發者ID:zykls,項目名稱:whynot,代碼行數:32,代碼來源:heterogeneous_utils.py

示例7: lineplot_multi_fig

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def lineplot_multi_fig(
    outer_key,
    data,
    xcol,
    ycols,
    ci,
    in_split_keys,
    plot_cfg=None,
    data_fns=None,
    plot_fns=None,
    **kwargs,
):
    """General method for line plotting TensorBoard datasets with smoothing and subsampling.

    Returns one figure for each plot."""
    if plot_fns is None:
        plot_fns = []

    # Aggregate data and convert to 'tidy' or longform format Seaborn expects
    longform = _aggregate_data(data, xcol, ycols, in_split_keys, data_fns)

    # Plot one figure per ycol
    for ycol in ycols:
        gridspec = {
            "left": 0.22,
            "bottom": 0.22,
        }
        fig, ax = plt.subplots(gridspec_kw=gridspec)

        sns.lineplot(x=xcol, y=ycol, data=longform, ci=ci, linewidth=1, label="Adv", **kwargs)
        for plot_fn in plot_fns:
            plot_fn(locals(), ax)

        yield (ycol,), fig 
開發者ID:HumanCompatibleAI,項目名稱:adversarial-policies,代碼行數:36,代碼來源:training.py

示例8: plot_train_result

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def plot_train_result(self):
        """Function to plot the training result."""
        algo = self.algo_list
        path = self.config.path_result
        result = self.config.path_figures
        data = [self.config.dataset_name]
        
        files = os.listdir(str(path))
        files_lwcase = [f.lower() for f in files]
        for d in data:
            df = pd.DataFrame()
            for a in algo:
                file_no = len([c for c in files_lwcase if a.lower() in c if 'training' in c])
                if file_no < 1:
                    continue
                file_path = str(path / (a.lower() + '_Training_results_' + str(file_no - 1) + '.csv'))
                if os.path.exists(file_path):
                    with open(str(path / (a.lower() + '_Training_results_' + str(file_no - 1) + '.csv')), 'r') as fh:
                        df_2 = pd.read_csv(fh)
                    if df.empty:
                        df['Epochs'] = df_2['Epochs']
                        df['Loss'] = df_2['Loss']
                        df['Algorithm'] = [a] * len(df_2)
                    else:
                        df_3 = pd.DataFrame()
                        df_3['Epochs'] = df_2['Epochs']
                        df_3['Loss'] = df_2['Loss']
                        df_3['Algorithm'] = [a] * len(df_2)
                        frames = [df, df_3]
                        df = pd.concat(frames)
            plt.figure()
            ax = seaborn.lineplot(x="Epochs", y="Loss", hue="Algorithm", markers=True, dashes=False, data=df)
            files = os.listdir(str(result))
            files_lwcase = [f.lower() for f in files]
            file_no = len([c for c in files_lwcase if d.lower() in c if 'training' in c])
            plt.savefig(str(result / (d + '_training_loss_plot_' + str(file_no) + '.pdf')), bbox_inches='tight', dpi=300)
            # plt.show() 
開發者ID:Sujit-O,項目名稱:pykg2vec,代碼行數:39,代碼來源:visualization.py

示例9: plot_average

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def plot_average(self, event_type, center='Peak', time_before=1,
                     time_after=1, filt=(None, None), figsize=(6, 4.5),
                     **kwargs):
        """plot_average (not for REM, spindles & SW only)"""
        import seaborn as sns
        import matplotlib.pyplot as plt

        df_sync = self.get_sync_events(center=center, time_before=time_before,
                                       time_after=time_after,
                                       filt=filt)

        assert not df_sync.empty, "Could not calculate event-locked data."

        if event_type == 'spindles':
            title = "Average spindle"
        else:  # "sw":
            title = "Average SW"

        # Start figure
        fig, ax = plt.subplots(1, 1, figsize=figsize)
        sns.lineplot(data=df_sync, x='Time', y='Amplitude', hue='Channel',
                     ax=ax, **kwargs)
        # ax.legend(frameon=False, loc='lower right')
        ax.set_xlim(df_sync['Time'].min(), df_sync['Time'].max())
        ax.set_title(title)
        ax.set_xlabel('Time (sec)')
        ax.set_ylabel('Amplitude (uV)')
        return ax


#############################################################################
# SPINDLES DETECTION
############################################################################# 
開發者ID:raphaelvallat,項目名稱:yasa,代碼行數:35,代碼來源:main.py

示例10: create_threshold_graph

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def create_threshold_graph(data):
    """
    display threshold analysis graph
    :param data:
    :return: None
    """
    sns.set(rc={"figure.figsize": (20.7, 10.27)})
    plt.ylim(0, 1.1)
    plt.axvline(0.2, 0, 1)
    plot = sns.lineplot(data=data, palette="tab10", linewidth=3.5)
    plt.setp(plot.legend().get_texts(), fontsize="22")
    plot.set_xlabel("Threshold T", fontsize=18)
    plot.set_ylabel("Metrics mentioned above", fontsize=18) 
開發者ID:watson-developer-cloud,項目名稱:assistant-dialog-skill-analysis,代碼行數:15,代碼來源:confidence_analyzer.py

示例11: get_df_for_env

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def get_df_for_env(gym_id):
    env_total_timesteps = envs[gym_id+"total_timesteps"]
    env_increment = env_total_timesteps / 500
    envs_same_x_axis = []
    for sampled_run in envs[gym_id]:
        df = pd.DataFrame(columns=sampled_run.columns)
        x_axis = [i*env_increment for i in range(500-2)]
        current_row = 0
        for timestep in x_axis:
            while sampled_run.iloc[current_row]["global_step"] < timestep:
                current_row += 1
                if current_row > len(sampled_run)-2:
                    break
            if current_row > len(sampled_run)-2:
                break
            temp_row = sampled_run.iloc[current_row].copy()
            temp_row["global_step"] = timestep
            df = df.append(temp_row)
        
        envs_same_x_axis += [df]
    return pd.concat(envs_same_x_axis, ignore_index=True)

# uncommenet the following to generate all figures
# for env in set(all_df["gym_id"]):
#     data = get_df_for_env(env)
#     sns.lineplot(data=data, x="global_step", y=feature_of_interest, hue="algo", ci='sd')
#     plt.legend(fontsize=6)
#     plt.title(env)
#     plt.savefig(f"{env}.svg")
#     plt.clf()

# debugging 
開發者ID:vwxyzjn,項目名稱:cleanrl,代碼行數:34,代碼來源:plot_benchmark.py

示例12: plot_spread

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def plot_spread(df, ticker1, ticker2, idx, th, stop):

    px1 = df[ticker1].iloc[idx] / df[ticker1].iloc[idx[0]]
    px2 = df[ticker2].iloc[idx] / df[ticker2].iloc[idx[0]]

    sns.set(style='white')

    # Set plotting figure
    fig, ax = plt.subplots(2, 1, gridspec_kw={'height_ratios': [2, 1]})

    # Plot the 1st subplot
    sns.lineplot(data=[px1, px2], linewidth=1.2, ax=ax[0])
    ax[0].legend(loc='upper left')

    # Calculate the spread and other thresholds
    spread = df[ticker1].iloc[idx] - df[ticker2].iloc[idx]
    mean_spread = spread.mean()
    sell_th     = mean_spread + th
    buy_th      = mean_spread - th
    sell_stop   = mean_spread + stop
    buy_stop    = mean_spread - stop

    # Plot the 2nd subplot
    sns.lineplot(data=spread, color='#85929E', ax=ax[1], linewidth=1.2)
    ax[1].axhline(sell_th,   color='b', ls='--', linewidth=1, label='sell_th')
    ax[1].axhline(buy_th,    color='r', ls='--', linewidth=1, label='buy_th')
    ax[1].axhline(sell_stop, color='g', ls='--', linewidth=1, label='sell_stop')
    ax[1].axhline(buy_stop,  color='y', ls='--', linewidth=1, label='buy_stop')
    ax[1].fill_between(idx, sell_th, buy_th, facecolors='r', alpha=0.3)
    ax[1].legend(loc='upper left', labels=['Spread', 'sell_th', 'buy_th', 'sell_stop', 'buy_stop'], prop={'size':6.5}) 
開發者ID:wai-i,項目名稱:Pair-Trading-Reinforcement-Learning,代碼行數:32,代碼來源:Analysis.py

示例13: visualize

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def visualize(result, name):
    # (N_samples=5, timesteps=200, types)
    result = np.array(result)
    assert result.shape[2] == 2
    # ax = sns.tsplot(data=result, condition=['OptNet', 'Adam'], linestyle='--')

    def trans(series):
        # (N_samples, timesteps)
        x = np.tile(np.arange(series.shape[1]) + 1,
                    (series.shape[0], 1)).flatten()
        y = series.flatten()
        return {'x': x, 'y': y}
    ax = sns.lineplot(label='OptNet', **trans(result[:, :, 0]))
    ax = sns.lineplot(label='Adam', ax=ax, **trans(result[:, :, 1]))
    ax.lines[-1].set_linestyle('-')
    ax.legend()
    plt.yscale('log'), plt.xlabel('steps')
    plt.ylabel('loss'), plt.title('MNIST')
    plt.ylim(0.09, 3.0)
    plt.xlim(1, result.shape[1])
    plt.grid(which='both', alpha=0.6, color='black', linewidth=0.1,
             linestyle='-')
    ax.tick_params(which='both', direction='in')
    ax.tick_params(which='major', length=8)
    ax.tick_params(which='minor', length=3)
    ax.xaxis.set_minor_locator(AutoMinorLocator(5))

    plt.show()
    plt.savefig(name)
    plt.close() 
開發者ID:chainer,項目名稱:models,代碼行數:32,代碼來源:train_mnist.py

示例14: lineplot_message_length

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def lineplot_message_length(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [avg([len(msg.text) for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [avg([len(msg.text) for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = sns.lineplot(x=x, y=y_your, palette="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    sns.lineplot(x=x, y=y_target, linewidth=2.5, label=target_name)

    ax.set(xlabel=xlabel, ylabel="average message length (characters)")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_message_length.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_message_length.__name__} was created.") 
開發者ID:vlajnaya-mol,項目名稱:message-analyser,代碼行數:30,代碼來源:plotter.py

示例15: lineplot_messages

# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import lineplot [as 別名]
def lineplot_messages(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [len([msg for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [len([msg for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = sns.lineplot(x=x, y=y_your, palette="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    sns.lineplot(x=x, y=y_target, linewidth=2.5, label=target_name)

    ax.set(xlabel=xlabel, ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_messages.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_messages.__name__} was created.") 
開發者ID:vlajnaya-mol,項目名稱:message-analyser,代碼行數:30,代碼來源:plotter.py


注:本文中的seaborn.lineplot方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。