本文整理匯總了Python中seaborn.tsplot方法的典型用法代碼示例。如果您正苦於以下問題:Python seaborn.tsplot方法的具體用法?Python seaborn.tsplot怎麽用?Python seaborn.tsplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類seaborn
的用法示例。
在下文中一共展示了seaborn.tsplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: plot_time_series
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_time_series(df, target, tag='eda', directory=None):
r"""Plot time series data.
Parameters
----------
df : pandas.DataFrame
The dataframe containing the ``target`` feature.
target : str
The target variable for the time series plot.
tag : str
Unique identifier for the plot.
directory : str, optional
The full specification of the plot location.
Returns
-------
None : None.
References
----------
http://seaborn.pydata.org/generated/seaborn.tsplot.html
"""
logger.info("Generating Time Series Plot")
# Generate the time series plot
ts_plot = sns.tsplot(data=df[target])
ts_fig = ts_plot.get_figure()
# Save the plot
write_plot('seaborn', ts_fig, 'time_series_plot', tag, directory)
#
# Function plot_candlestick
#
示例2: plot_avg_return
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_avg_return(file_name, granularity):
plotting_data = torch.load(file_name + "_processed_data")
returns = plotting_data['returns']
unique_frames = plotting_data['unique_frames']
x_len = len(unique_frames)
x_index = [i for i in numpy.arange(0, x_len, granularity)]
x = unique_frames[::granularity]
y = numpy.transpose(numpy.array(returns)[x_index, :])
f, ax = plt.subplots(1, 1, figsize=[3, 2], dpi=300)
sns.set_style("ticks")
sns.set_context("paper")
# Find the order of magnitude of the last frame
order = int(math.log10(unique_frames[-1]))
range_frames = int(unique_frames[-1]/ (10**order))
sns.tsplot(data=y, time=numpy.array(x)/(10**order), color='b')
ax.set_xticks(numpy.arange(range_frames + 1))
plt.show()
f.savefig(file_name + "_avg_return.pdf", bbox_inches="tight")
plt.close(f)
示例3: roc_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def roc_plot(fpr, tpr):
""" Plot 1-Specificity by Sensitivity
Args:
fpr: false positive rate from Roc.calculate
tpr: true positive rate from Roc.calculate
Returns:
fig: Will return a matplotlib ROC plot
"""
plt.figure()
plt.plot(fpr, tpr, color="red", linewidth=3)
# fig = sns.tsplot(tpr,fpr,color='red',linewidth=3)
plt.xlabel("(1 - Specificity)", fontsize=16)
plt.ylabel("Sensitivity", fontsize=16)
plt.title("ROC Plot", fontsize=18)
return
示例4: plot_data
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [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()
示例5: plot_data
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_data(data, value="AverageReturn"):
if isinstance(data, list):
data = pd.concat(data, ignore_index=True)
sns.set(style="darkgrid", font_scale=1.5)
sns.tsplot(data=data, time="Iteration", value=value, unit="Unit", condition="Condition")
plt.legend(loc='best').draggable()
plt.show()
示例6: plot_work_trajectories
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_work_trajectories(self, environment, filename):
"""
Plot the NCMC work trajectories for the given environment and each attempted transition
Parameters
----------
environment : str
Name of environment
filename : str
Name of output file
"""
w_t = {state_transition : [] for state_transition in self._state_transitions[environment]}
for iteration in range(self._n_exen_iterations[environment]):
logP_ncmc_trajectory = self._ncfile.groups[environment]['NCMCEngine']['protocolwork'][iteration, :]
state_key = self._storage.get_object(environment, "ExpandedEnsembleSampler", "state_key", iteration)
proposed_state_key = self._storage.get_object(environment, "ExpandedEnsembleSampler", "proposed_state_key", iteration)
if state_key == proposed_state_key:
continue
w_t[(state_key, proposed_state_key)].append(-logP_ncmc_trajectory)
w_t_stacked = {state_transition: np.stack(work_trajectories) for state_transition, work_trajectories in w_t.items()}
with PdfPages(filename) as pdf:
sns.set(font_scale=2)
for state_transition, work_array in w_t_stacked.items():
fig = plt.figure(figsize=(28, 12))
ax1 = sns.tsplot(work_array, color="Blue")
iupac_transition = self._state_transition_to_iupac(state_transition)
plt.title("{} => {} transition {} work trajectory".format(iupac_transition[0], iupac_transition[1], "NCMC"))
plt.xlabel("step (1fs)")
plt.ylabel("Work / kT")
plt.tight_layout()
pdf.savefig(fig)
plt.close()
示例7: plot_data
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_data(data, value="AverageReturn"):
if isinstance(data, list):
data = pd.concat(data, ignore_index=True)
sns.set(style="darkgrid", font_scale=1.5)
sns.tsplot(data=data, time="Iteration", value=value, unit="Unit", condition="Condition")
plt.legend(loc='best').draggable()
plt.show()
示例8: visualize
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [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()
示例9: plot_reward_by_episode
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_reward_by_episode(self, ax=None):
self.make_palette()
full_data = pd.DataFrame()
for idx, (benchmark_data, name) in enumerate(self.benchmarks):
plot_data = to_timeseries(benchmark_data, x_label="Episode", y_label="Average Episode Reward",
target=rewards_by_episode, cut_x=benchmark_data.min_x('episodes'), smooth=10)
plot_data['Benchmark'] = name
full_data = full_data.append(plot_data)
plot = sns.tsplot(data=full_data, time="Episode", value="Average Episode Reward", unit="experiment",
condition='Benchmark', ax=ax, ci=[68, 95], color=self.palette)
return plot
示例10: plot_reward_by_timestep
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_reward_by_timestep(self, ax=None):
self.make_palette()
full_data = pd.DataFrame()
for idx, (benchmark_data, name) in enumerate(self.benchmarks):
plot_data = to_timeseries(benchmark_data, x_label="Time step", y_label="Average Episode Reward",
target=rewards_by_timestep, cut_x=benchmark_data.min_x('timesteps'), smooth=10)
plot_data['Benchmark'] = name
full_data = full_data.append(plot_data)
plot = sns.tsplot(data=full_data, time="Time step", value="Average Episode Reward", unit="experiment",
condition='Benchmark', ax=ax, ci=[68, 95], color=self.palette)
return plot
示例11: plot_reward_by_second
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_reward_by_second(self, ax=None):
self.make_palette()
full_data = pd.DataFrame()
for idx, (benchmark_data, name) in enumerate(self.benchmarks):
plot_data = to_timeseries(benchmark_data, x_label="Second", y_label="Average Episode Reward",
target=rewards_by_second, cut_x=benchmark_data.min_x('seconds'), smooth=10)
plot_data['Benchmark'] = name
full_data = full_data.append(plot_data)
plot = sns.tsplot(data=full_data, time="Second", value="Average Episode Reward", unit="experiment",
condition='Benchmark', ax=ax, ci=[68, 95], color=self.palette)
return plot
示例12: plot_roc_curve_from_df
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_roc_curve_from_df(
df, auc_dict_list=None, output_filepath=None, figsize=(6, 6)
):
"""From a df with multiple methods plot a roc curve using sns.tspot."""
xlabel = 'False Discovery Rate'
ylabel = 'True Positive Rate'
title = 'Receiver Operating Characteristic'
# rename method name to include AUC to show it in legend
if auc_dict_list:
for method in auc_dict_list.keys():
mean_auc = np.mean(auc_dict_list[method])
method_indices = df['method'] == method
df['mean_auc'] = mean_auc
df.loc[method_indices, 'method'] = (
'{} '.format(
method.capitalize()
if method != 'INtERAcT'
else method
) +
'AUC=%0.2f' % mean_auc
)
df = df.sort_values(by='method')
df.rename(columns={'method': ''}, inplace=True) # to avoid legend title
plt.figure(figsize=figsize)
sns.set_style("whitegrid", {'axes.grid': False})
sns.tsplot(
data=df, time='XX', value='YY',
condition='', unit='pathway', legend=True
)
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
if output_filepath:
plt.savefig(output_filepath, bbox_inches='tight')
示例13: calibration_plot
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def calibration_plot(
fraction_positives,
mean_predicted_values,
algorithm_names=None,
filename=None
):
assert len(fraction_positives) == len(mean_predicted_values)
sns.set_style('whitegrid')
colors = plt.get_cmap('tab10').colors
num_algorithms = len(fraction_positives)
plt.figure(figsize=(9, 9))
plt.grid(which='both')
plt.grid(which='minor', alpha=0.5)
plt.grid(which='major', alpha=0.75)
plt.plot([0, 1], [0, 1], 'k:', label='Perfectly calibrated')
for i in range(num_algorithms):
# ax1.plot(mean_predicted_values[i], fraction_positives[i],
# label=algorithms[i] if algorithm_names is not None and i < len(algorithms) else '')
# sns.tsplot(mean_predicted_values[i], fraction_positives[i], ax=ax1, color=colors[i])
assert len(mean_predicted_values[i]) == len(fraction_positives[i])
order = min(3, len(mean_predicted_values[i]) - 1)
sns.regplot(mean_predicted_values[i], fraction_positives[i],
order=order, x_estimator=np.mean, color=colors[i],
marker='o', scatter_kws={'s': 40},
label=algorithm_names[
i] if algorithm_names is not None and i < len(
algorithm_names) else '')
ticks = np.linspace(0.0, 1.0, num=11)
plt.xlim([-0.05, 1.05])
plt.xticks(ticks)
plt.xlabel('Predicted probability')
plt.ylabel('Observed probability')
plt.ylim([-0.05, 1.05])
plt.yticks(ticks)
plt.legend(loc='lower right')
plt.title('Calibration (reliability curve)')
plt.tight_layout()
ludwig.contrib.contrib_command("visualize_figure", plt.gcf())
if filename:
plt.savefig(filename)
else:
plt.show()
示例14: plot_data
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
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)
#plt.legend(loc='upper center', ncol=3, handlelength=1,
# borderaxespad=0., prop={'size': 13})
"""
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)
示例15: plot_kdes_from_bs
# 需要導入模塊: import seaborn [as 別名]
# 或者: from seaborn import tsplot [as 別名]
def plot_kdes_from_bs(x:np.ndarray, bs_stats:Dict[str,Any], name2args:Dict[str,Dict[str,Any]],
feat:str, units:Optional[str]=None, moments=True,
savename:Optional[str]=None, settings:PlotSettings=PlotSettings()) -> None:
r'''
Plots KDEs computed via :meth:`~lumin.utils.statistics.bootstrap_stats`
Arguments:
bs_stats: (filtered) dictionary retruned by :meth:`~lumin.utils.statistics.bootstrap_stats`
name2args: Dictionary mapping names of different distributions to arguments to pass to seaborn tsplot
feat: Name of feature being plotted (for axis lablels)
units: Optional units to show on axes
moments: whether to display mean and standard deviation of each distribution
savename: Optional name of file to which to save the plot of feature importances
settings: :class:`~lumin.plotting.plot_settings.PlotSettings` class to control figure appearance
'''
# TODO: update to sns 9
with sns.axes_style(**settings.style), sns.color_palette(settings.cat_palette) as palette:
plt.figure(figsize=(settings.w_mid, settings.h_mid))
for i, name in enumerate(name2args):
if 'color' not in name2args[name]: name2args[name]['color'] = palette[i]
if 'label' in name2args[name]:
name2args[name]['condition'] = name2args[name]['label']
name2args[name].pop('label')
if 'condition' in name2args[name] and moments:
mean, mean_unc = uncert_round(np.mean(bs_stats[f'{name}_mean']), np.std(bs_stats[f'{name}_mean'], ddof=1))
std, std_unc = uncert_round(np.mean(bs_stats[f'{name}_std']), np.std(bs_stats[f'{name}_std'], ddof=1))
name2args[name]['condition'] += r', $\overline{x}=' + r'{}\pm{}\ \sigma= {}\pm{}$'.format(mean, mean_unc, std, std_unc)
sns.tsplot(data=bs_stats[f'{name}_kde'], time=x, **name2args[name])
plt.legend(loc=settings.leg_loc, fontsize=settings.leg_sz)
y_lbl = r'$\frac{1}{N}\ \frac{dN}{d' + feat.replace('$','') + r'}$'
if units is not None:
x_lbl = feat + r'$\ [' + units + r']$'
y_lbl += r'$\ [' + units + r'^{-1}]$'
else:
x_lbl = feat
plt.xlabel(x_lbl, fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.ylabel(y_lbl, fontsize=settings.lbl_sz, color=settings.lbl_col)
plt.xticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.yticks(fontsize=settings.tk_sz, color=settings.tk_col)
plt.title(settings.title, fontsize=settings.title_sz, color=settings.title_col, loc=settings.title_loc)
if savename is not None: plt.savefig(settings.savepath/f'{savename}{settings.format}', bbox_inches='tight')
plt.show()