Python seaborn.set_context() Examples

The following are 30 code examples of seaborn.set_context(). 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: evals.py    From acnn with GNU General Public License v3.0 6 votes vote down vote up
def plot_kim_curve(tmp):
    sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 5})
    sns.set_style("darkgrid")

    plt.figure(figsize=(20, 10))
    plt.hold('on')
    plt.plot(np.linspace(0, 0.3, 100), tmp['kc_avg'])
    plt.ylim([0, 1])

#    plt.figure(figsize=(10,5))
#    plt.hold('on')
#    legend = []
#    for k,v in bench_res.iteritems():
#        plt.plot(np.linspace(0, 0.3, 100), v['kc_avg'])
#        legend.append(k)
#    plt.ylim([0, 1])
#    plt.legend(legend, loc='lower right') 
Example #2
Source File: common.py    From typhon with MIT License 6 votes vote down vote up
def _plot_weights(self, title, file, layer_index=0, vmin=-5, vmax=5):
        import seaborn as sns
        sns.set_context("paper")

        layers = self.iwp.estimator.steps[-1][1].coefs_
        layer = layers[layer_index]
        f, ax = plt.subplots(figsize=(18, 12))
        weights = pd.DataFrame(layer)
        weights.index = self.iwp.inputs

        sns.set(font_scale=1.1)

        # Draw a heatmap with the numeric values in each cell
        sns.heatmap(
            weights, annot=True, fmt=".1f", linewidths=.5, ax=ax,
            cmap="difference", center=0, vmin=vmin, vmax=vmax,
            # annot_kws={"size":14},
        )
        ax.tick_params(labelsize=18)
        f.tight_layout()
        f.savefig(file) 
Example #3
Source File: plot_return.py    From MinAtar with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: plotting.py    From fitbit-analyzer with Apache License 2.0 6 votes vote down vote up
def plotSleepValueHeatmap(intradayStats, sleepValue=1):
    sns.set_context("poster")
    sns.set_style("darkgrid")

    xTicksDiv = 20
    #stepSize = int(len(xticks)/xTicksDiv)
    stepSize = 60
    xticks = [x for x in intradayStats.columns.values]
    keptticks = xticks[::stepSize]
    xticks = ['' for _ in xticks]
    xticks[::stepSize] = keptticks
    plt.figure(figsize=(16, 4.2))
    g = sns.heatmap(intradayStats.loc[sleepValue].reshape(1,-1))
    g.set_xticklabels(xticks, rotation=45)
    g.set_yticklabels([])
    g.set_ylabel(sleepStats.SLEEP_VALUES[sleepValue])
    plt.tight_layout()
    sns.plt.show() 
Example #5
Source File: plotting.py    From floris with Apache License 2.0 6 votes vote down vote up
def __init__(self):

        sns.set_style("ticks")
        sns.set_context("paper", font_scale=1.5)

        # color palette from colorbrewer (up to 4 colors, good for print and black&white printing)
        # color_brewer_palette = ['#e66101', '#5e3c99', '#fdb863', '#b2abd2']

        # most journals: 300dpi
        plt.rcParams["savefig.dpi"] = 300

        # most journals: 9 cm (or 3.5 inch) for single column width and 18.5 cm (or 7.3 inch) for double column width.
        plt.rcParams["figure.autolayout"] = False
        plt.rcParams["figure.figsize"] = 7.3, 4
        plt.rcParams["axes.labelsize"] = 16
        plt.rcParams["axes.titlesize"] = 16
        plt.rcParams["xtick.labelsize"] = 16
        plt.rcParams["ytick.labelsize"] = 16
        plt.rcParams["font.size"] = 32
        plt.rcParams["lines.linewidth"] = 2.0
        plt.rcParams["lines.markersize"] = 8
        plt.rcParams["legend.fontsize"] = 14 
Example #6
Source File: runner.py    From geoseg with MIT License 6 votes vote down vote up
def learning_curve(self, idxs=[2,3,5,6]):
        import seaborn as sns
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')
        # set style
        sns.set_context("paper", font_scale=1.5,)
        # sns.set_style("ticks", {
        #     "font.family": "Times New Roman",
        #     "font.serif": ["Times", "Palatino", "serif"]})

        for idx in idxs:
            plt.plot(self.logs[self.args.trigger],
                     self.logs[self.header[idx]], label=self.header[idx])
        plt.ylabel(" {} / {} ".format(repr(self.criterion), repr(self.evaluator)))
        if self.args.trigger == 'epoch':
            plt.xlabel("Epochs")
        else:
            plt.xlabel("Iterations")
        plt.suptitle("Training log of {}".format(self.method))
        # remove top&left line
        # sns.despine()
        plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
        plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.png'.format(self.repr)),
                    format='png', bbox_inches='tight', dpi=144) 
Example #7
Source File: experiment.py    From double-dqn with MIT License 6 votes vote down vote up
def plot_evaluation_episode_reward():
	pylab.clf()
	sns.set_context("poster")
	pylab.plot(0, 0)
	episodes = [0]
	average_scores = [0]
	median_scores = [0]
	for n in xrange(len(csv_evaluation)):
		params = csv_evaluation[n]
		episodes.append(params[0])
		average_scores.append(params[1])
		median_scores.append(params[2])
	pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("average score")
	pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir)

	pylab.clf()
	pylab.plot(0, 0)
	pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("median score")
	pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir) 
Example #8
Source File: ABuEnv.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def init_plot_set():
    """全局plot设置"""
    import seaborn as sns
    sns.set_context('notebook', rc={'figure.figsize': g_plt_figsize})
    sns.set_style("darkgrid")

    import matplotlib
    # conda 5.0后需要添加单独matplotlib的figure设置否则pandas的plot size不生效
    matplotlib.rcParams['figure.figsize'] = g_plt_figsize 
Example #9
Source File: plot_utils.py    From celer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def configure_plt():
    rc('font', **{'family': 'sans-serif',
                  'sans-serif': ['Computer Modern Roman']})
    params = {'axes.labelsize': 12,
              'font.size': 12,
              'legend.fontsize': 12,
              'xtick.labelsize': 10,
              'ytick.labelsize': 10,
              'text.usetex': True,
              'figure.figsize': (8, 6)}
    plt.rcParams.update(params)

    sns.set_palette('colorblind')
    sns.set_context("poster")
    sns.set_style("ticks") 
Example #10
Source File: document.py    From DQLearning-Toolbox with MIT License 5 votes vote down vote up
def savePair(df,samplesize=20000):
    df1 = df.sample(samplesize)
    sns.set(style="ticks")
    sns.set_context("paper")
    sns.pairplot(df1)
    plt.title('Pair Graph')
    plt.savefig(pair_path)

#画滑动平均图,默认12阶 
Example #11
Source File: __init__.py    From pyani with MIT License 5 votes vote down vote up
def heatmap(dfr, outfilename=None, title=None, params=None):
    """Return seaborn heatmap with cluster dendrograms.

    :param dfr:  pandas DataFrame with relevant data
    :param outfilename:  path to output file (indicates output format)
    :param title:
    :param params:
    """
    # Decide on figure layout size: a minimum size is required for
    # aesthetics, and a maximum to avoid core dumps on rendering.
    # If we hit the maximum size, we should modify font size.
    maxfigsize = 120
    calcfigsize = dfr.shape[0] * 1.1
    figsize = min(max(8, calcfigsize), maxfigsize)
    if figsize == maxfigsize:
        scale = maxfigsize / calcfigsize
        sns.set_context("notebook", font_scale=scale)

    # Add a colorbar?
    if params.classes is None:
        col_cb = None
    else:
        col_cb = get_colorbar(dfr, params.classes)

    # Add attributes to parameter object, and draw heatmap
    params.colorbar = col_cb
    params.figsize = figsize
    params.linewidths = 0.25
    fig = get_clustermap(dfr, params, title=title)

    # Save to file
    if outfilename:
        fig.savefig(outfilename)

    # Return clustermap
    return fig 
Example #12
Source File: esrunner.py    From geoseg with MIT License 5 votes vote down vote up
def learning_curve(self, idxs=[2,3,5,6]):
        import seaborn as sns
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')
        # set style
        sns.set_context("paper", font_scale=1.5,)
        # sns.set_style("ticks", {
        #     "font.family": "Times New Roman",
        #     "font.serif": ["Times", "Palatino", "serif"]})

        for idx in idxs:
            plt.plot(self.logs[self.args.trigger],
                     self.logs[self.header[idx]], label=self.header[idx])
        plt.ylabel(" {} / {} ".format(repr(self.criterion), repr(self.evaluator)))
        if self.args.trigger == 'epoch':
            plt.xlabel("Epochs")
        else:
            plt.xlabel("Iterations")
        plt.suptitle("Training log of {}".format(self.method))
        # remove top&left line
        # sns.despine()
        plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
        plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.png'.format(self.repr)),
                    format='png', bbox_inches='tight', dpi=144)
        # plt.savefig(os.path.join(Logs_DIR, 'curve', '{}.eps'.format(self.repr)),
        #             format='eps', bbox_inches='tight', dpi=300)
        return 0 
Example #13
Source File: words2map.py    From words2map with MIT License 5 votes vote down vote up
def generate_clusters(words, vectors_in_2D, print_status=True):
	# HDBSCAN, i.e. hierarchical density-based spatial clustering of applications with noise (https://github.com/lmcinnes/hdbscan)
	vectors = vectors_in_2D
	sns.set_context('poster')
	sns.set_color_codes()
	plot_kwds = {'alpha' : 0.5, 's' : 500, 'linewidths': 0}
	clusters = HDBSCAN(min_cluster_size=2).fit_predict(vectors)
	palette = sns.color_palette("husl", np.unique(clusters).max() + 1)
	colors = [palette[cluster_index] if cluster_index >= 0 else (0.0, 0.0, 0.0) for cluster_index in clusters]
	fig = plt.figure(figsize=(30, 30))
	plt.scatter(vectors.T[0], vectors.T[1], c=colors, **plot_kwds)
	plt.axis('off')
	x_vals = [i[0] for i in vectors]
	y_vals = [i[1] for i in vectors]
	plt.ylim(min(y_vals)-0.3, max(y_vals)+0.3)    
	plt.xlim(min(x_vals)-0.3, max(x_vals)+0.3) 
	font_path = getcwd() + '/fonts/Comfortaa-Regular.ttf'
	font_property = matplotlib.font_manager.FontProperties(fname=font_path, size=24)
	for i, word in enumerate(words):
		if type(word) != type(None):
			if type(word) != type(""):
				word = unidecode(word).replace("_", " ")
			else:
				word = word.replace("_", " ")
			text_object = plt.annotate(word, xy=(x_vals[i], y_vals[i]+0.05), font_properties=font_property, color=colors[i], ha="center")
	plt.subplots_adjust(left=(500/3000), right=(2900/3000), top=1.0, bottom=(300/2700))
	plt.savefig(get_visualization_file_path(print_status), bbox_inches="tight")
	return clusters 
Example #14
Source File: c7.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def sample_711():
    """
    7.1.1 趋势跟踪和均值回复的周期重叠性
    :return:
    """

    sns.set_context(rc={'figure.figsize': (14, 7)})
    sns.regplot(x=np.arange(0, kl_pd.shape[0]), y=kl_pd.close.values, marker='+')
    plt.show()

    from abupy import ABuRegUtil
    deg = ABuRegUtil.calc_regress_deg(kl_pd.close.values)
    plt.show()
    print('趋势角度:' + str(deg))

    start = 0
    # 前1/4的数据
    end = int(kl_pd.shape[0] / 4)
    # 将x也使用arange切割
    x = np.arange(start, end)
    # y根据start,end进行切片
    y = kl_pd.close.values[start:end]
    sns.regplot(x=x, y=y, marker='+')
    plt.show()

    start = int(kl_pd.shape[0] / 4)
    # 向前推1/4单位个时间
    end = start + int(kl_pd.shape[0] / 4)
    sns.regplot(x=np.arange(start, end), y=kl_pd.close.values[start:end],
                marker='+')
    plt.show() 
Example #15
Source File: simple.py    From qstrader with MIT License 5 votes vote down vote up
def plot_results(self):
        """
        A simple script to plot the balance of the portfolio, or
        "equity curve", as a function of time.
        """
        sns.set_palette("deep", desat=.6)
        sns.set_context(rc={"figure.figsize": (8, 4)})

        # Plot two charts: Equity curve, period returns
        fig = plt.figure()
        fig.patch.set_facecolor('white')

        df = pd.DataFrame()
        df["equity"] = pd.Series(self.equity, index=self.timeseries)
        df["equity_returns"] = pd.Series(self.equity_returns, index=self.timeseries)
        df["drawdowns"] = pd.Series(self.drawdowns, index=self.timeseries)

        # Plot the equity curve
        ax1 = fig.add_subplot(311, ylabel='Equity Value')
        df["equity"].plot(ax=ax1, color=sns.color_palette()[0])

        # Plot the returns
        ax2 = fig.add_subplot(312, ylabel='Equity Returns')
        df['equity_returns'].plot(ax=ax2, color=sns.color_palette()[1])

        # drawdown, max_dd, dd_duration = self.create_drawdowns(df["Equity"])
        ax3 = fig.add_subplot(313, ylabel='Drawdowns')
        df['drawdowns'].plot(ax=ax3, color=sns.color_palette()[2])

        # Rotate dates
        fig.autofmt_xdate()

        # Plot the figure
        plt.show() 
Example #16
Source File: utils.py    From pysster with MIT License 5 votes vote down vote up
def _set_sns_context(n_kernel):
    import seaborn as sns
    if n_kernel <= 25:
        sns.set_context("notebook", rc={"ytick.labelsize":26})
    elif 25 < n_kernel <= 50:
        sns.set_context("notebook", rc={"ytick.labelsize":22})
    elif 50 < n_kernel <= 75:
        sns.set_context("notebook", rc={"ytick.labelsize":14})
    elif 75 < n_kernel <= 100:
        sns.set_context("notebook", rc={"ytick.labelsize":8})
    else:
        sns.set_context("notebook", rc={"ytick.labelsize":5}) 
Example #17
Source File: utils.py    From jira-agile-metrics with MIT License 5 votes vote down vote up
def set_chart_context(context):
    sns.set_context(context) 
Example #18
Source File: experiment.py    From double-dqn with MIT License 5 votes vote down vote up
def plot_episode_reward():
	pylab.clf()
	sns.set_context("poster")
	pylab.plot(0, 0)
	episodes = [0]
	scores = [0]
	for n in xrange(len(csv_episode)):
		params = csv_episode[n]
		episodes.append(params[0])
		scores.append(params[1])
	pylab.plot(episodes, scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("score")
	pylab.savefig("%s/episode_reward.png" % args.plot_dir) 
Example #19
Source File: slashdot_results.py    From news-popularity-prediction with Apache License 2.0 5 votes vote down vote up
def make_slashdot_figures(output_path_prefix, method_name_list, slashdot_mse, slashdot_jaccard, slashdot_k_list):
    sns.set_style("darkgrid")
    sns.set_context("paper")

    translator = get_method_name_to_legend_name_dict()

    slashdot_k_list = list(slashdot_k_list)

    fig, axes = plt.subplots(1, 2, sharex=True)

    axes[0].set_title("SlashDot Comments")
    axes[1].set_title("SlashDot Users")

    plt.locator_params(nbins=8)

    # Comments
    for m, method in enumerate(method_name_list):
        axes[0].set_ylabel("MSE")
        axes[0].set_xlabel("Lifetime (sec)")
        axes[0].plot(slashdot_k_list[1:],
                     handle_nan(slashdot_mse[method]["comments"].mean(axis=1))[1:],
                     label=translator[method])

    # Users
    for m, method in enumerate(method_name_list):
        # axes[1].set_ylabel("MSE")
        axes[1].set_xlabel("Lifetime (sec)")
        axes[1].plot(slashdot_k_list[1:],
                     handle_nan(slashdot_mse[method]["users"].mean(axis=1))[1:],
                     label=translator[method])


    axes[1].legend(loc="upper right")

    # plt.show()
    plt.savefig(output_path_prefix + "_mse_slashdot_SNOW" + ".png", format="png")
    plt.savefig(output_path_prefix + "_mse_slashdot_SNOW" + ".eps", format="eps") 
Example #20
Source File: slashdot_results.py    From news-popularity-prediction with Apache License 2.0 5 votes vote down vote up
def make_barrapunto_figures(output_path_prefix, method_name_list, barrapunto_mse, barrapunto_jaccard, barrapunto_k_list):
    sns.set_style("darkgrid")
    sns.set_context("paper")

    translator = get_method_name_to_legend_name_dict()

    barrapunto_k_list = list(barrapunto_k_list)

    fig, axes = plt.subplots(1, 2, sharex=True)

    axes[0].set_title("BarraPunto Comments")
    axes[1].set_title("BarraPunto Users")

    plt.locator_params(nbins=8)

    # Comments
    for m, method in enumerate(method_name_list):
        axes[0].set_ylabel("MSE")
        axes[0].set_xlabel("Lifetime (sec)")
        axes[0].plot(barrapunto_k_list[1:],
                        handle_nan(barrapunto_mse[method]["comments"].mean(axis=1))[1:],
                        label=translator[method])

    # Users
    for m, method in enumerate(method_name_list):
        # axes[1].set_ylabel("MSE")
        axes[1].set_xlabel("Lifetime (sec)")
        axes[1].plot(barrapunto_k_list[1:],
                        handle_nan(barrapunto_mse[method]["users"].mean(axis=1))[1:],
                        label=translator[method])


    axes[1].legend(loc="upper right")

    # plt.show()
    plt.savefig(output_path_prefix + "_mse_barrapunto_SNOW" + ".png", format="png")
    plt.savefig(output_path_prefix + "_mse_barrapunto_SNOW" + ".eps", format="eps") 
Example #21
Source File: charting.py    From jira-metrics-extract with MIT License 5 votes vote down vote up
def set_context(context="talk"):
    sns.set_context(context) 
Example #22
Source File: nonparametric_plots.py    From numpy-ml with GNU General Public License v3.0 5 votes vote down vote up
def plot_gp():
    np.random.seed(12345)
    sns.set_context("paper", font_scale=0.65)

    X_test = np.linspace(-10, 10, 100)
    X_train = np.array([-3, 0, 7, 1, -9])
    y_train = np.sin(X_train)

    fig, axes = plt.subplots(2, 2)
    alphas = [0, 1e-10, 1e-5, 1]
    for ix, (ax, alpha) in enumerate(zip(axes.flatten(), alphas)):
        G = GPRegression(kernel="RBFKernel", alpha=alpha)
        G.fit(X_train, y_train)
        y_pred, conf = G.predict(X_test)

        ax.plot(X_train, y_train, "rx", label="observed")
        ax.plot(X_test, np.sin(X_test), label="true fn")
        ax.plot(X_test, y_pred, "--", label="MAP (alpha={})".format(alpha))
        ax.fill_between(X_test, y_pred + conf, y_pred - conf, alpha=0.1)
        ax.set_xticks([])
        ax.set_yticks([])
        sns.despine()

        ax.legend()

    plt.tight_layout()
    plt.savefig("img/gp_alpha.png", dpi=300)
    plt.close("all") 
Example #23
Source File: app.py    From smallrnaseq with GNU General Public License v3.0 5 votes vote down vote up
def plot_results(res, path):
    """Some results plots"""

    if res is None or len(res) == 0:
        return
    counts = base.pivot_count_data(res, idxcols=['name','ref'])
    x = base.get_fractions_mapped(res)
    print (x)
    import seaborn as sns
    sns.set_style('white')
    sns.set_context("paper",font_scale=1.2)
    fig = plotting.plot_fractions(x)
    fig.savefig(os.path.join(path,'libraries_mapped.png'))
    fig = plotting.plot_sample_counts(counts)
    fig.savefig(os.path.join(path,'total_per_sample.png'))
    fig = plotting.plot_read_count_dists(counts)
    fig.savefig(os.path.join(path,'top_mapped.png'))
    scols,ncols = base.get_column_names(counts)
    for l,df in counts.groupby('ref'):
        if 'mirbase' in l:
            fig = plotting.plot_read_count_dists(df)
            fig.savefig(os.path.join(path,'top_%s.png' %l))
    #if len(scols)>1:
    #    fig = plotting.expression_clustermap(counts)
    #    fig.savefig(os.path.join(path,'expr_map.png'))
    return 
Example #24
Source File: experiment.py    From double-dqn with MIT License 5 votes vote down vote up
def plot_training_episode_highscore():
	pylab.clf()
	sns.set_context("poster")
	pylab.plot(0, 0)
	episodes = [0]
	highscore = [0]
	for n in xrange(len(csv_training_highscore)):
		params = csv_training_highscore[n]
		episodes.append(params[0])
		highscore.append(params[1])
	pylab.plot(episodes, highscore, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("highscore")
	pylab.savefig("%s/training_episode_highscore.png" % args.plot_dir) 
Example #25
Source File: plot.py    From pipedream with MIT License 5 votes vote down vote up
def plot(values, epochs_to_plot, ylimit, ylabel, output_filepath):
    import matplotlib
    matplotlib.use('Agg')
    from matplotlib import pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    import seaborn as sns
    matplotlib.rc('text', usetex=True)
    sns.set_style('ticks')
    sns.set_style({'font.family':'sans-serif'})
    flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8']
    sns.set_palette(flatui)
    paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10}
    sns.set_context("paper", font_scale=3,  rc=paper_rc)
    current_palette = sns.color_palette()

    plt.figure(figsize=(10, 4))
    ax = plt.subplot2grid((1, 1), (0, 0), colspan=1)

    for epoch_to_plot in epochs_to_plot:
        values_to_plot = values[epoch_to_plot]
        ax.plot(range(len(values_to_plot)), values_to_plot,
                label="Epoch %d" % epoch_to_plot,
                linewidth=2)
    ax.set_xlim([0, None])
    ax.set_ylim([0, ylimit])

    ax.set_xlabel("Layer ID")
    ax.set_ylabel(ylabel)
    plt.legend()

    with PdfPages(output_filepath) as pdf:
        pdf.savefig(bbox_inches='tight') 
Example #26
Source File: graph.py    From pipedream with MIT License 5 votes vote down vote up
def plot_cdfs(self, cdfs, output_directory):
        import matplotlib
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        from matplotlib.backends.backend_pdf import PdfPages
        import seaborn as sns
        matplotlib.rc('text', usetex=True)
        sns.set_style('ticks')
        sns.set_style({'font.family':'sans-serif'})
        flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8']
        sns.set_palette(flatui)
        paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10}
        sns.set_context("paper", font_scale=3,  rc=paper_rc)
        current_palette = sns.color_palette()

        plt.figure(figsize=(10, 4))
        ax = plt.subplot2grid((1, 1), (0, 0), colspan=1)

        labels = ["Compute", "Activations", "Parameters"]
        for i in range(3):
            cdf = [cdfs[j][i] for j in range(len(cdfs))]
            ax.plot(range(len(cdfs)), cdf,  label=labels[i],
                    linewidth=2)
        ax.set_xlim([0, None])
        ax.set_ylim([0, 100])

        ax.set_xlabel("Layer ID")
        ax.set_ylabel("CDF (\%)")
        plt.legend()

        with PdfPages(os.path.join(output_directory, "cdf.pdf")) as pdf:
            pdf.savefig(bbox_inches='tight') 
Example #27
Source File: test_scalability.py    From iroko with Apache License 2.0 4 votes vote down vote up
def plot_scalability_graph(increments, data_dirs, plot_dir, name):
    # Set seaborn style for plotting
    sns.set(style="whitegrid", rc={"lines.linewidth": 2.5})
    sns.set_context("paper")
    files = increments
    increments = [0] + increments
    agg_df = pd.DataFrame({'Number of Hosts': increments})
    for data_dir in data_dirs.keys():
        bw_list = {}
        bw_list["rx"] = []
        bw_list["tx"] = []
        for increment in files:
            stats_file = '%s/%s_hosts/runtime_statistics.npy' % (
                data_dir, increment)
            log.info("Loading %s..." % stats_file)
            try:
                with FileLock(stats_file + ".lock"):
                    statistics = np.load(stats_file).item()
            except Exception:
                log.info("Error loading file %s" % stats_file)
                continue
            port_stats = np.moveaxis(statistics["stats"], 0, -1)
            port_rx_bws = np.array(
                port_stats[STATS_DICT["bw_rx"]].mean(axis=1))
            port_tx_bws = np.array(
                port_stats[STATS_DICT["bw_tx"]].mean(axis=1))
            # bandwidths
            log.info("Computing mean of interface bandwidth per step.")
            bw_list["rx"].append(port_rx_bws.sum())
            bw_list["tx"].append(port_tx_bws.sum())
        bw_list["rx"] = [0] + bw_list["rx"]
        bw_list["tx"] = [0] + bw_list["tx"]
        agg_bw = np.add(bw_list["rx"], bw_list["tx"])
        t_df = pd.DataFrame({data_dirs[data_dir]: agg_bw})
        agg_df = pd.concat((agg_df, t_df), axis=1)
    agg_df.set_index('Number of Hosts', inplace=True)
    fig = sns.lineplot(data=agg_df, markers=True, markersize=8)
    fig.set_xscale('symlog', basex=2, linthreshx=4)
    fig.set_yscale('symlog', basey=2, linthreshy=4 * 10e6)
    fig.set(xlabel='Hosts', ylabel='Mbps (Avg)')
    y_increments = np.array(increments) * 10e6
    fig.set_yticks(y_increments)
    fig.set_yticklabels(increments)
    fig.set_xticks(increments)
    fig.set_xticklabels(increments)
    fig.set_ylim(ymin=0, ymax=y_increments[len(y_increments) - 1] + 100)
    fig.set_xlim(xmin=0, xmax=increments[len(increments) - 1] + 100)

    log.info("Test Summary:")
    log.info(agg_df)

    plt_name = "%s/" % (plot_dir)
    plt_name += "%s" % name
    log.info("Saving plot %s" % plt_name)
    check_plt_dir(plt_name)
    plt.savefig(plt_name + ".pdf", bbox_inches='tight', pad_inches=0.05)
    plt.savefig(plt_name + ".png", bbox_inches='tight', pad_inches=0.05)
    plt.gcf().clear() 
Example #28
Source File: plot.py    From iroko with Apache License 2.0 4 votes vote down vote up
def plot_lineplot(algos, plt_stats, num_samples, plt_name):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns

    # Set seaborn style for plotting
    sns.set(style="ticks", rc={"lines.linewidth": 1.2,
                               "axes.spines.right": False,
                               "axes.spines.top": False,
                               'lines.markeredgewidth': 0.1, })
    # sns.set_context("paper")
    metrics = {}
    plt_metrics = ["reward", "queues", "bw"]
    log.info("Converting numpy arrays into pandas dataframes.")
    metrics["reward"] = np_dict_to_pd(plt_stats, "rewards")
    metrics["actions"] = np_dict_to_pd(plt_stats, "actions")
    metrics["queues"] = np_dict_to_pd(plt_stats, "backlog")
    metrics["bw"] = np_dict_to_pd(plt_stats, "bw_tx")
    log.info("Computing overlimit deltas.")
    metrics["overlimits"] = np_dict_to_pd(plt_stats, "olimit").diff()
    log.info("Computing drops deltas.")
    metrics["drops"] = np_dict_to_pd(plt_stats, "drops").diff()

    fig, ax = plt.subplots(len(plt_metrics), 1, sharex=True, squeeze=True)
    mean_smoothing = math.ceil(num_samples / 100)
    if (num_samples > 10000):
        sample = 10000
    else:
        sample = num_samples
    num_subplots = len(ax)
    marker_range = list(np.arange(
        math.ceil(sample / 10), sample, math.ceil(sample / 10)))
    for index, metric in enumerate(plt_metrics):
        metric_df = metrics[metric]
        log.info("Drop overlimit rows %s." % metric)
        metric_df = metric_df.drop(metric_df.index[num_samples:])
        log.info("Computing rolling %s." % metric)
        metric_df = compute_rolling_df_mean(metric_df, mean_smoothing)
        log.info("Normalizing %s." % metric)
        metric_df = normalize_df_min_max(metric_df)
        log.info("Plotting %s..." % metric)
        if index == 0:
            plt_legend = "brief"
        else:
            plt_legend = False
        ax[index] = sns.lineplot(data=metric_df,
                                 ax=ax[index], legend=plt_legend,
                                 markers=True, markevery=marker_range,
                                 style="event")
        ax[index].set_ylabel(metric)
        if index == num_subplots - 1:
            ax[index].set_xlabel("Time")
        ax[index].set_xlim([0, num_samples])
        ax[index].margins(y=0.15)
    ax[0].legend(bbox_to_anchor=(0.5, 1.45), loc="upper center",
                 fancybox=True, shadow=True, ncol=len(algos))
    log.info("Saving plot %s" % plt_name)
    plt.savefig(plt_name + ".pdf", bbox_inches='tight', pad_inches=0.05)
    plt.savefig(plt_name + ".png", bbox_inches='tight', pad_inches=0.05)
    plt.gcf().clear() 
Example #29
Source File: graph.py    From pipedream with MIT License 4 votes vote down vote up
def plot_bar_graph(self, all_values, ylabel, legend, output_template, output_directory):
        import matplotlib
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        from matplotlib.backends.backend_pdf import PdfPages
        import seaborn as sns
        matplotlib.rc('text', usetex=True)
        sns.set_style('ticks')
        sns.set_style({'font.family':'sans-serif'})
        flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8']
        sns.set_palette(flatui)
        paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10}
        sns.set_context("paper", font_scale=3,  rc=paper_rc)
        current_palette = sns.color_palette()

        labels = ["Compute_times", "Activations", "Parameters"]
        ylabels = ["Compute time\n(milliseconds)", "Activation size\n(bytes)", "Parameter size\n(bytes)"]
        for i in range(3):
            plt.figure(figsize=(10, 4))
            ax = plt.subplot2grid((1, 1), (0, 0), colspan=1)

            values_sum = sum([all_values[j][i] for j in range(len(all_values))])
            # Truncate the number of values plotted, since bars become very thin otherwise.
            values = [all_values[j][i] for j in range(len(all_values))][:400]
            if legend:
                ax.bar(range(len(values)), values, label="Sum: %.1f" % values_sum)
            else:
                ax.bar(range(len(values)), values)
            ax.set_xlim([0, None])
            ax.set_ylim([0, None])

            ax.set_xlabel("Layer ID")
            if ylabel is not None:
                ax.set_ylabel(ylabel)
            else:
                ax.set_ylabel(ylabels[i])
            if legend:
                plt.legend()

            with PdfPages(os.path.join(output_directory,
                          (output_template % labels[i].lower()))) as pdf:
                pdf.savefig(bbox_inches='tight') 
Example #30
Source File: analyze_sampling.py    From SAMPL6 with MIT License 4 votes vote down vote up
def plot_restraint_and_barostat_analysis():
    """Plot the Figure showing info for the restraint and barostat analysis."""
    import seaborn as sns
    from matplotlib import pyplot as plt
    sns.set_style('whitegrid')
    sns.set_context('paper', font_scale=1.0)

    # Create two columns, each of them share the x-axis.
    fig = plt.figure(figsize=(7.25, 4))
    # Restraint distribution axes.
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(223, sharex=ax1)
    barostat_axes = [ax1, ax2]
    # Volume distribution axes.
    ax3 = fig.add_subplot(222)
    ax4 = fig.add_subplot(224, sharex=ax3)
    restraint_axes = [ax3, ax4]

    # Plot barostat analysis.
    plot_volume_distributions(barostat_axes, plot_predicted=True)

    # Plot restraint analysis.
    system_id = 'OA-G3-0'
    plot_restraint_analysis(system_id, restraint_axes)
    # Configure axes.
    restraint_axes[0].set_xlim((0, 10.045))
    restraint_axes[1].set_ylim((-7, -3.9))

    for ax in restraint_axes + barostat_axes:
        ax.tick_params(axis='x', which='major', pad=0.1)
        ax.tick_params(axis='y', which='major', pad=0.1)
    plt.tight_layout(pad=0.3)

    # plt.show()
    output_file_path = os.path.join(SAMPLING_PAPER_DIR_PATH, 'Figure5-restraint_barostat',
                                    'restraint_barostat.pdf')
    os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
    plt.savefig(output_file_path)


# =============================================================================
# FIGURE 6 - HREX INITIAL BIAS
# =============================================================================