Python seaborn.lineplot() Examples
The following are 30
code examples of seaborn.lineplot().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
seaborn
, or try the search function
.
Example #1
Source File: plot.py From berkeleydeeprlcourse-homework-pytorch with MIT License | 6 votes |
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()
Example #2
Source File: plotUtils.py From pyodds with MIT License | 6 votes |
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()
Example #3
Source File: stock_visualizer.py From stock-analysis with MIT License | 6 votes |
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 )
Example #4
Source File: utils.py From dca with Apache License 2.0 | 6 votes |
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]
Example #5
Source File: analyze_action.py From L2RPN with GNU Lesser General Public License v3.0 | 6 votes |
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()
Example #6
Source File: planners_evaluation.py From rl-agents with MIT License | 5 votes |
def plot_all(data_file, directory, data_range): print("Reading data from {}".format(directory / data_file)) df = pd.read_csv(str(directory / data_file)) df = df[~df.agent.isin(['agent'])].apply(pd.to_numeric, errors='ignore') df = df.sort_values(by="agent") m = df.loc[df['simple_regret'] != np.inf, 'simple_regret'].max() df['simple_regret'].replace(np.inf, m, inplace=True) df = rename_df(df) if data_range: start, end = data_range.split(':') df = df[df["budget"].between(int(start), int(end))] print("Number of seeds found: {}".format(df.seed.nunique())) try: for field in [#"total_reward", "return", "length", "mean_return", "simple_regret"]: fig, ax = plt.subplots() ax.set(xscale="log") if field in ["simple_regret"]: ax.set_yscale("symlog", linthreshy=1e-2) sns.lineplot(x=rename("budget"), y=rename(field), ax=ax, hue="agent", data=df) ax.yaxis.set_minor_locator(LogLocator(base=10, subs="all")) ax.yaxis.grid(True, which='minor', linestyle='--') plt.legend(loc="lower left") field_path = directory / "{}.pdf".format(field) fig.savefig(field_path, bbox_inches='tight') field_path = directory / "{}.png".format(field) fig.savefig(field_path, bbox_inches='tight') print("Saving {} plot to {}".format(field, field_path)) except ValueError as e: print(e) custom_processing(df, directory)
Example #7
Source File: analyze.py From rl-agents with MIT License | 5 votes |
def analyze(self): self.find_best_run() for field in ["total reward", "length", "crashed", "speed", "distance"]: logging.info("Analyzing {}".format(field)) fig, ax = plt.subplots() sns.lineplot(x="episode", y=field, hue="agent", data=self.data, ax=ax, ci=95) field_path = self.out / "{}.pdf".format(field) fig.savefig(field_path, bbox_inches='tight') plt.show() plt.close()
Example #8
Source File: viz.py From gluon-face with MIT License | 5 votes |
def plot_accuracy(accs, threholds): sns.set(style="darkgrid") plt.figure(figsize=(8, 8)) plt.xlabel("threshold") plt.ylabel("accuracy") plt.title("Accuracy") sns.lineplot(x="threshold", y="accuracy", data={"accuracy": accs, "threshold": threholds}) plt.show()
Example #9
Source File: viz.py From gluon-face with MIT License | 5 votes |
def plot_roc(tpr, fpr, x_name="FPR", y_name="TPR"): sns.set(style="darkgrid") plt.figure(figsize=(8, 8)) plt.xlabel(x_name) plt.ylabel(y_name) plt.title("ROC") sns.lineplot(x=x_name, y=y_name, data={x_name: fpr, y_name: tpr}) plt.show()
Example #10
Source File: plot.py From firedup with MIT License | 5 votes |
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) plt.legend( loc="upper center", ncol=3, handlelength=1, borderaxespad=0.0, prop={"size": 13} ).set_draggable(True) 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 #11
Source File: thesis_charts.py From yelp with GNU Lesser General Public License v2.1 | 5 votes |
def plot_divergence(): prefix = Constants.RESULTS_FOLDER + Constants.ITEM_TYPE + \ '_topic_model_divergence' csv_file_path = prefix + '.csv' json_file_path = prefix + '.json' data_frame = pandas.read_csv(csv_file_path) # data_frame.drop(columns=['cycle_time'], inplace=True) # data_frame['num_topics'].astype('category') # data_frame['bow_type'].fillna('All', inplace=True) data_frame.rename(columns={'divergence': 'Divergence'}, inplace=True) # data_frame = data_frame.loc[data_frame[ # Constants.TOPIC_MODEL_TARGET_REVIEWS_FIELD] == Constants.SPECIFIC] print(data_frame.describe()) print(data_frame.head()) # g = seaborn.lineplot( # x='num_topics', y='divergence', # data=data_frame) seaborn.set_style("darkgrid") data_frame.plot.line(x='num_topics', y='Divergence') plt.xlabel('Number of topics') plt.ylabel('Divergence') # plt.ylim(0, 6) # plt.xlim(2, 12) # g.figure.savefig(prefix + '.pdf') plt.savefig(prefix + '.pdf') # plt.show()
Example #12
Source File: plot_util.py From ns4_chatbot with Apache License 2.0 | 5 votes |
def draw_it(title, x_label, y_label, data,x_start=0,x_end=24,image_path=".cache/image"): # print(data) f, ax = plt.subplots() logger.debug("数据:%r", data) for c in data: logger.debug("开始画 数据分类:%r",c) _data = data[c] _data = np.array(_data)#有可能传入的是个数组,所以要转换成ndarray sns.lineplot(marker='o', data=_data, err_style="bars", label=c) ax.xaxis.set_major_locator(MultipleLocator(1)) ax.xaxis.set_minor_locator(MultipleLocator(1)) # ax.yaxis.set_major_locator(MultipleLocator(5)) # ax.yaxis.set_minor_locator(MultipleLocator(1)) ax.tick_params(axis='x', colors='b') plt.xlim((x_start,x_end)) plt.ylim(bottom=1) #plt.xlim((0,24)) plt.xticks(fontsize=10) plt.legend(loc='upper right') plt.title(title, fontsize='large', fontweight='bold') # 设置字体大小与格式 plt.xlabel(x_label, fontsize=10) plt.ylabel(y_label, fontsize=10) # plt.show() random_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8)) temp_file = image_path + "/" + random_file_name + ".jpg" logger.debug("将图片保存到文件:%s", temp_file) f.savefig(temp_file, dpi=100, bbox_inches='tight') return temp_file
Example #13
Source File: plot.py From SCALE with MIT License | 5 votes |
def lineplot(data, name, title='', cbar=False): sns.lineplot(x='fraction', y=name, hue='method', data=data, markers=True, style='method', sort=False) plt.title(title) if cbar: plt.legend(loc='right', bbox_to_anchor=(1.25, 0.2), frameon=False) else: plt.legend().set_visible(False) plt.show()
Example #14
Source File: plotter.py From message-analyser with MIT License | 5 votes |
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.")
Example #15
Source File: plotter.py From message-analyser with MIT License | 5 votes |
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.")
Example #16
Source File: train_mnist.py From models with MIT License | 5 votes |
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()
Example #17
Source File: Analysis.py From Pair-Trading-Reinforcement-Learning with MIT License | 5 votes |
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})
Example #18
Source File: plot_benchmark.py From cleanrl with MIT License | 5 votes |
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
Example #19
Source File: confidence_analyzer.py From assistant-dialog-skill-analysis with Apache License 2.0 | 5 votes |
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)
Example #20
Source File: heterogeneous_utils.py From whynot with MIT License | 5 votes |
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()
Example #21
Source File: main.py From yasa with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_average(self, center='NegPeak', time_before=0.4, time_after=0.8, filt=(None, None), figsize=(6, 4.5), **kwargs): """ Plot the average slow-wave. Parameters ---------- center : str Landmark of the event to synchronize the timing on. Default is to use the negative peak of the slow-wave. time_before : float Time (in seconds) before ``center``. time_after : float Time (in seconds) after ``center``. filt : tuple Optional filtering to apply to data. For instance, ``filt=(1, 30)`` will apply a 1 to 30 Hz bandpass filter, and ``filt=(None, 40)`` will apply a 40 Hz lowpass filter. Filtering is done using default parameters in the :py:func:`mne.filter.filter_data` function. figsize : tuple Figure size in inches. **kwargs : dict Optional argument that are passed to :py:func:`seaborn.lineplot`. """ return super().plot_average(event_type='sw', center=center, time_before=time_before, time_after=time_after, filt=filt, figsize=figsize, **kwargs) ############################################################################# # REMs DETECTION #############################################################################
Example #22
Source File: main.py From yasa with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_average(self, center='Peak', time_before=1, time_after=1, filt=(None, None), figsize=(6, 4.5), **kwargs): """ Plot the average spindle. Parameters ---------- center : str Landmark of the event to synchronize the timing on. Default is to use the most prominent peak of the spindle. time_before : float Time (in seconds) before ``center``. time_after : float Time (in seconds) after ``center``. filt : tuple Optional filtering to apply to data. For instance, ``filt=(1, 30)`` will apply a 1 to 30 Hz bandpass filter, and ``filt=(None, 40)`` will apply a 40 Hz lowpass filter. Filtering is done using default parameters in the :py:func:`mne.filter.filter_data` function. figsize : tuple Figure size in inches. **kwargs : dict Optional argument that are passed to :py:func:`seaborn.lineplot`. """ return super().plot_average(event_type='spindles', center=center, time_before=time_before, time_after=time_after, filt=filt, figsize=figsize, **kwargs) ############################################################################# # SLOW-WAVES DETECTION #############################################################################
Example #23
Source File: main.py From yasa with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #############################################################################
Example #24
Source File: visualization.py From pykg2vec with MIT License | 5 votes |
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()
Example #25
Source File: analysis.py From hpg with MIT License | 5 votes |
def plot(i, exp, df, directory): sns.set_style('darkgrid') ax = sns.lineplot(x='evaluation step', y='average return', hue='method', data=df) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1)) ax.set_title(json.dumps(exp, sort_keys=True)) ax.set_xlim(xmin=0) ax.figure.savefig(os.path.join(directory, 'experiment_{0}.pdf'.format(i)), bbox_inches='tight', dpi=300) ax.figure.clf()
Example #26
Source File: utility.py From es_on_gke with Apache License 2.0 | 5 votes |
def save_scores(log_dir, n_iter, scores): """Save scores to file system. Save scores to file system as a csv file. Args: log_dir: str. Path to log directory. n_iter: int. Current iteration number. scores: np.array. Scores. """ # save scores for analysis in the future filename = os.path.join(log_dir, 'scores.csv') df = pd.DataFrame({'Time': [int(time.time())] * scores.size, 'Iteration': [n_iter] * scores.size, 'Reward': scores}) need_header = not os.path.exists(filename) df.to_csv(filename, mode='a', header=need_header, index=False) # draw graphs df = pd.read_csv(filename) sns.set() # plot 1: reward vs iteration sns_plot = sns.lineplot(x='Iteration', y='Reward', data=df, ci='sd') im_filename = os.path.join(log_dir, 'reward_vs_iteration.png') sns_plot.get_figure().savefig(im_filename) plt.clf() # plot 2: reward vs time start_time = df.Time.values[0] df.Time = (df.Time - start_time) / 3600 # convert to hours sns_plot = sns.lineplot(x='Time', y='Reward', data=df, ci='sd') sns_plot.set_xlabel('Time (hour)') im_filename = os.path.join(log_dir, 'reward_vs_time.png') sns_plot.get_figure().savefig(im_filename) plt.clf()
Example #27
Source File: training.py From adversarial-policies with MIT License | 5 votes |
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
Example #28
Source File: showMatLabFig._spatioTemporal.py From python-urbanPlanning with MIT License | 4 votes |
def graphMerge(num_meanDis_DF): plt.clf() import plotly.express as px from plotly.offline import plot #01-draw scatter paring # coore_columns=["number","mean distance","PHMI"] # fig = px.scatter_matrix(num_meanDis_DF[coore_columns],width=1800, height=800) # # fig.show() #show in jupyter # plot(fig) #02-draw correlation using plt.matshow-A # Corrcoef=np.corrcoef(np.array(num_meanDis_DF[coore_columns]).transpose()) #sns_columns=["number","mean distance","PHMI"] # print(Corrcoef) # plt.matshow(num_meanDis_DF[coore_columns].corr()) # plt.xticks(range(len(coore_columns)), coore_columns) # plt.yticks(range(len(coore_columns)), coore_columns) # plt.colorbar() # plt.show() #03-draw correlation -B # Compute the correlation matrix # plt.clf() # corr_columns_b=["number","mean distance","PHMI"] # corr = num_meanDis_DF[corr_columns_b].corr() corr = num_meanDis_DF.corr() # # Generate a mask for the upper triangle # mask = np.triu(np.ones_like(corr, dtype=np.bool)) # # Set up the matplotlib figure # f, ax = plt.subplots(figsize=(11, 9)) # # Generate a custom diverging colormap # cmap = sns.diverging_palette(220, 10, as_cmap=True) # # Draw the heatmap with the mask and correct aspect ratio # sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={"shrink": .5}) #04 # Draw a heatmap with the numeric values in each cell plt.clf() sns.set() f, ax = plt.subplots(figsize=(15, 13)) sns.heatmap(corr, annot=True, fmt=".2f", linewidths=.5, ax=ax) #04-draw curves # plt.clf() # sns_columns=["number","mean distance","PHMI"] # sns.set(rc={'figure.figsize':(25,3)}) # sns.lineplot(data=num_meanDis_DF[sns_columns], palette="tab10", linewidth=2.5) #rpy2调用R编程,参考:https://rpy2.github.io/doc/v2.9.x/html/introduction.html
Example #29
Source File: plot.py From teachDeepRL with MIT License | 4 votes |
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').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 #30
Source File: utils.py From dca with Apache License 2.0 | 4 votes |
def plot_mean_dropout(ad, title, ax, opt_zinb_theta=False, legend_out=False): expr = ad.X mu = expr.mean(0) do = np.mean(expr == 0, 0) v = expr.var(axis=0) coefs, r2 = _fitquad(mu, v) theta = 1.0/coefs[0] # zinb fit coefs = _optimize_zinb(mu, do, theta=theta if not opt_zinb_theta else None) print(coefs) #pois_pred = np.exp(-mu) nb_pred = nb_zero(theta, mu) zinb_pred = zinb_zero(coefs[2], mu, sigmoid((np.log(mu+1e-7)*coefs[0])+coefs[1])) # calculate log loss for all distr. #pois_ll = log_loss(pois_pred, do) nb_ll = log_loss(nb_pred, do) zinb_ll = log_loss(zinb_pred, do) ax.plot(mu, do, 'o', c='black', markersize=1) ax.set(xscale="log") #sns.lineplot(mu, pois_pred, ax=ax, color='blue') sns.lineplot(mu, nb_pred, ax=ax, color='red') sns.lineplot(mu, zinb_pred, ax=ax, color='green') ax.set_title(title) ax.set_ylabel('Empirical dropout rate') ax.set_xlabel(r'Mean expression') leg_loc = 'best' if not legend_out else 'upper left' leg_bbox = None if not legend_out else (1.02, 1.) ax.legend(['Genes', #r'Poisson $L=%.4f$' % pois_ll, r'NB($\theta=%.2f)\ L=%.4f$' % ((1./theta), nb_ll), r'ZINB($\theta=%.2f,\pi=\sigma(%.2f\mu%+.2f)) \ L=%.4f$' % (1.0/coefs[2], coefs[0], coefs[1], zinb_ll)], loc=leg_loc, bbox_to_anchor=leg_bbox) zinb_pval = _lrt(-zinb_ll, -nb_ll, 3, 1) print('p-value: %e' % zinb_pval)