jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_data(data, xaxis="Epoch", value="AverageEpRet", condition="Condition1", smooth=1, env_name=None, **kwargs):
	if smooth > 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)

	flatui = ["#4B72B0", "#55A868", "#C44E51", "#8172B1", "#E377C1", "#64B4CD", "#FF7400"]
	sns.set(style="white", palette=sns.color_palette(flatui), color_codes=False, font_scale=1.5)
	ax = sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)
	
	ax.set_xlabel("Steps")
	ax.set_xlim([0.0, 3000000.0])

	if env_name is not None:
		ax.set_title(label=env_name)
	plt.legend(loc="best").set_draggable(True)
	plt.tick_params(direction="out", length=4)

	xscale = np.max(np.asarray(data[xaxis])) > 5e3
	if xscale:
		plt.ticklabel_format(style="sci", axis='x', scilimits=(0, 0))

	plt.tight_layout(pad=0.5)
//  [python]
def local_metric_over_trajectory(y_hat, key=None, *, ylim=(-0.05, 1.05), xlim=None):
    """Visualizing the sample trajectories in a 2-dimensional domain

    :param y_hat: Size(Batch, Timesteps, 1), the score for the trajectory
    :param key: file key to which the figure is saved.
    :param ylim: vertical limits to the plot
    :return:
    """
    import matplotlib.pyplot as plt
    import seaborn as sns
    from ml_logger import logger

    from matplotlib import rcParams
    rcParams['axes.titlepad'] = 15
    rcParams['axes.labelpad'] = 12
    rcParams['axes.labelsize'] = 12

    DPI = 300
    title = "Local Metric Over Trajectory"

    plt.figure(figsize=(3, 2), dpi=DPI, )
    plt.title(title)

    plt.ylabel("Score")
    plt.xlabel("Time Steps Apart")

    sns.tsplot(y_hat, time=range(y_hat.shape[1]), ci=[75, 100], color="#23aaff")
    plt.ylim(*ylim)
    if xlim:
        plt.xlim(*xlim)
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['top'].set_visible(False)

    if key is None:
        plt.show()
    else:
        logger.savefig(key, bbox_inches='tight')
    plt.close()
//  [python]
def local_metric_over_trajectory(y_hat, key=None, *, ylim=(-0.05, 1.05), xlim=None):
    """Visualizing the sample trajectories in a 2-dimensional domain

    :param y_hat: Size(Batch, Timesteps, 1), the score for the trajectory
    :param key: file key to which the figure is saved.
    :param ylim: vertical limits to the plot
    :return:
    """
    import matplotlib.pyplot as plt
    import seaborn as sns
    from ml_logger import logger

    from matplotlib import rcParams
    rcParams['axes.titlepad'] = 15
    rcParams['axes.labelpad'] = 12
    rcParams['axes.labelsize'] = 12

    DPI = 300
    title = "Local Metric Over Trajectory"

    plt.figure(figsize=(3, 2), dpi=DPI, )
    plt.title(title)

    plt.ylabel("Score")
    plt.xlabel("Time Steps Apart")

    sns.lineplot(x=range(y_hat.shape[1]), y=y_hat.mean(axis=0).squeeze(), ci=[75, 100], color="#23aaff")
    plt.ylim(*ylim)
    if xlim:
        plt.xlim(*xlim)
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['top'].set_visible(False)

    if key is None:
        plt.show()
    else:
        logger.savefig(key, bbox_inches='tight')
    plt.close()
//  [python]
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)
    # data = data.reindex()
    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)
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
    if smooth > 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='best').set_draggable(True)
    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
    plt.tight_layout(pad=0.5)
//  [python]
def plot_graph(rst_type,scenario):
    results = get_data(rst_type,scenario)
    fig = plt.figure()
    fig.set_size_inches(8,5)
    if rst_type == 'shprl':
        label = ['Baseline', 'Fixed 1400 Labels', 'Scaled 1400 Labels', 'Fixed 700 Labels', 'Scaled 700 Labels']
    else:
        label = ['Baseline', 'Scaled 1400 Labels (No agent predict)', r'Scaled 1400 Labels (30% agent predict)', r'Scaled 1400 Labels (50% agent predict)']
    sns.tsplot(time=results[0][0], data=results[0][1], condition=label[0], color='k', linestyle='-')
    sns.tsplot(time=results[1][0], data=results[1][1], condition=label[1], color='C0', linestyle='-')
    sns.tsplot(time=results[2][0], data=results[2][1], condition=label[2], color='C1', linestyle='-')
    sns.tsplot(time=results[3][0], data=results[3][1], condition=label[3], color='C2', linestyle='-')
    if rst_type == 'shprl':
        sns.tsplot(time=results[4][0], data=results[4][1], condition=label[4], color='C3', linestyle='-')

    plt.title(scenario, fontsize=20)
    plt.ylabel("Reward Value", fontsize=15)
    plt.xlabel(r'Timesteps $\times 10^7$', fontsize=15, labelpad = 0)
    plt.legend(loc='bottom right')
    plt.savefig('./output/{0}_{1}.png'.format(rst_type,scenario), dpi=200)
//  [python]
def plot_graph(rst_type,scenario):
    results = get_data(rst_type,scenario)
    fig = plt.figure()
    fig.set_size_inches(8,5)
    if rst_type == 'shprl':
        label = ['Baseline', 'Fixed 1400 Labels', 'Scaled 1400 Labels', 'Fixed 700 Labels', 'Scaled 700 Labels']
    else:
        label = ['Baseline', 'Scaled 1400 Labels (No agent predict)', r'Scaled 1400 Labels (30% agent predict)', r'Scaled 1400 Labels (50% agent predict)']
    sns.lineplot(x=results[0][0], y=results[0][1], label=label[0], color='k', linestyle='-')
    sns.lineplot(x=results[1][0], y=results[1][1], label=label[1], color='C0', linestyle='-')
    sns.lineplot(x=results[2][0], y=results[2][1], label=label[2], color='C1', linestyle='-')
    sns.lineplot(x=results[3][0], y=results[3][1], label=label[3], color='C2', linestyle='-')
    if rst_type == 'shprl':
        sns.lineplot(x=results[4][0], y=results[4][1], label=label[4], color='C3', linestyle='-')

    plt.title(scenario, fontsize=20)
    plt.ylabel("Reward Value", fontsize=15)
    plt.xlabel(r'Timesteps $\times 10^7$', fontsize=15, labelpad = 0)
    plt.legend(loc='bottom right')
    plt.savefig('./output/{0}_{1}.png'.format(rst_type,scenario), dpi=200)
//  [python]
def plot_loss_curves(train_loss_runs, validation_loss_runs, dataset_name, model_params):
    fontsize = 20
    def _tsplot(list_data, label, color):
        '''Wrapper method over tsplot'''
        data = np.asarray(list_data)
        y_axis = np.linspace(0, data.shape[1] - 1, data.shape[1])
        ax = sns.tsplot(data=data,
                        ci="sd",
                        color=color,
                        condition=[label],
                        legend=True,
                        time=y_axis,
                        )
        plt.setp(ax.get_legend().get_texts(), fontsize=fontsize)

        return ax

    train_ax = _tsplot(list_data=train_loss_runs,
                       color="b",
                       label="Loss for training data"
                       )

    val_ax = _tsplot(list_data=validation_loss_runs,
                     color="r",
                     label="Loss for validation data"
                     )
    val_ax.set(xlabel="Number of epochs", ylabel="Loss value")



    title = "Training and validation curve for {} dataset using {} model".format(
        dataset_name.capitalize(),
        model_params.model_name.upper())
    if(model_params.model_name in set([GCN, GCN_POLY, GCN_AE, GCN_VAE])):
        title = title+" with support size = " + str(model_params.support_size)

    for item in ([val_ax.xaxis.label, val_ax.yaxis.label] +
                     val_ax.get_xticklabels() +
                     val_ax.get_yticklabels()):
        item.set_fontsize(fontsize)

    plt.savefig(title + ".png", bbox_inches='tight')

    plt.show()
//  [python]
def plot_loss_curves(train_loss_runs, validation_loss_runs, dataset_name, model_params):
    fontsize = 20
    def _tsplot(list_data, label, color):
        '''Wrapper method over tsplot'''
        data = np.asarray(list_data)
        y_axis = np.linspace(0, data.shape[1] - 1, data.shape[1])
        ax = sns.lineplot(data=data,
                        ci="sd",
                        color=color,
                        label=label,
                        legend=True,
                        x=y_axis,
                        )
        plt.setp(ax.get_legend().get_texts(), fontsize=fontsize)

        return ax

    train_ax = _tsplot(list_data=train_loss_runs,
                       color="b",
                       label="Loss for training data"
                       )

    val_ax = _tsplot(list_data=validation_loss_runs,
                     color="r",
                     label="Loss for validation data"
                     )
    val_ax.set(xlabel="Number of epochs", ylabel="Loss value")



    title = "Training and validation curve for {} dataset using {} model".format(
        dataset_name.capitalize(),
        model_params.model_name.upper())
    if(model_params.model_name in set([GCN, GCN_POLY, GCN_AE, GCN_VAE])):
        title = title+" with support size = " + str(model_params.support_size)

    for item in ([val_ax.xaxis.label, val_ax.yaxis.label] +
                     val_ax.get_xticklabels() +
                     val_ax.get_yticklabels()):
        item.set_fontsize(fontsize)

    plt.savefig(title + ".png", bbox_inches='tight')

    plt.show()
//  [python]
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):
        # for df in data:
        #     df.rename(columns={"EpCost":"Cost","EpRet":"Reward", 
        #                             "TotalEnvInteracts":"Steps"}, inplace=True)
        data = pd.concat(data, ignore_index=True)
    #print(data.head())
    data.rename(columns={"EpCost":"Cost","EpRet":"Reward", "TotalEnvInteracts":"Steps"}, inplace=True)
    data.rename(columns={"AverageEpCost":"Cost","AverageEpRet":"Reward"}, inplace=True)
    xaxis = "Steps" if xaxis=="TotalEnvInteracts" else xaxis
    #print(value)
    value = "Cost" if value=="EpCost" or value=="AverageEpCost" else value
    value = "Reward" if value=="EpRet" or value=="AverageEpRet" else value

    #plt.figure(figsize=(16,8))
    
    sns.set(style="darkgrid", font_scale=1.5)
    sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', **kwargs)
    #sns.lineplot(data=data, x=xaxis, y=value, hue=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.
    """
    #sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
    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))
//  [python]
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):
        # for df in data:
        #     df.rename(columns={"EpCost":"Cost","EpRet":"Reward", 
        #                             "TotalEnvInteracts":"Steps"}, inplace=True)
        data = pd.concat(data, ignore_index=True)
    #print(data.head())
    data.rename(columns={"EpCost":"Cost","EpRet":"Reward", "TotalEnvInteracts":"Steps"}, inplace=True)
    data.rename(columns={"AverageEpCost":"Cost","AverageEpRet":"Reward"}, inplace=True)
    xaxis = "Steps" if xaxis=="TotalEnvInteracts" else xaxis
    #print(value)
    value = "Cost" if value=="EpCost" or value=="AverageEpCost" else value
    value = "Reward" if value=="EpRet" or value=="AverageEpRet" else value

    #plt.figure(figsize=(16,8))
    
    sns.set(style="darkgrid", font_scale=1.5)
    sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
    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))
//  [python]
print('p done..')

print(ttest_ind(sums_p,sums_s))
print(ttest_ind(sums_p,sums_r))
print(ttest_ind(sums_s,sums_r))

sns.tsplot(all_vals_r,color='g')
//  [python]
print('p done..')

print(ttest_ind(sums_p,sums_s))
print(ttest_ind(sums_p,sums_r))
print(ttest_ind(sums_s,sums_r))

sns.lineplot(data=all_vals_r,color='g')
//  [python]
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)
    # sns.lineplot(data=data, x=xaxis, y=value, 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)
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
    if smooth > 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='best').set_draggable(True)
    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))

    plt.tight_layout(pad=0.5)
//  [python]
def phase2_plot_update(f, ax1, data, passed, peak, hf1, hf2, progress):
    # Update the plot with latest measurement
    ax1.cla()
    freq_mhz = map(lambda x: x / 1e6, data.frequency)
    sns.tsplot(data.ch1, time=freq_mhz, ax=ax1, interpolate=True)
    ax1.plot(peak[0] / 1e6, peak[1], 'v')
    ax1.set(title='Beatnote Spectrum', xlabel='Frequency (MHz)',
            ylabel='Power (dBm)')
    ax1.annotate('Peak (%.2f MHz)\n'
                 'Linewidth (%.2f kHz)\n'
                 'Completed %d%%'
                 '' % (peak[0] / 1e6, (hf2[0] - hf1[0]) / 1e3, progress),
                 xy=(0.80, 0.90), xycoords='axes fraction', fontsize=14)
    ax1.axvspan(hf1[0] / 1e6, hf2[0] / 1e6,
                alpha=0.1, color='green' if passed else 'red')
    plt.pause(0.01)
//  [python]
def phase2_plot_update(f, ax1, data, passed, peak, hf1, hf2, progress):
    # Update the plot with latest measurement
    ax1.cla()
    freq_mhz = map(lambda x: x / 1e6, data.frequency)
    sns.lineplot(x=freq_mhz, y=data.ch1, ax=ax1, interpolate=True)
    ax1.plot(peak[0] / 1e6, peak[1], 'v')
    ax1.set(title='Beatnote Spectrum', xlabel='Frequency (MHz)',
            ylabel='Power (dBm)')
    ax1.annotate('Peak (%.2f MHz)\n'
                 'Linewidth (%.2f kHz)\n'
                 'Completed %d%%'
                 '' % (peak[0] / 1e6, (hf2[0] - hf1[0]) / 1e3, progress),
                 xy=(0.80, 0.90), xycoords='axes fraction', fontsize=14)
    ax1.axvspan(hf1[0] / 1e6, hf2[0] / 1e6,
                alpha=0.1, color='green' if passed else 'red')
    plt.pause(0.01)
//  [python]
def phase1_plot_update(f, ax1, ax2, data, passed, results, fails,
                       failure_criteria, progress):
    ax1.cla()
    ax2.cla()
    sns.tsplot(data.ch1, time=data.time, color="g" if passed else "r",
               ax=ax1, interpolate=True)
    if len(results) > 1:
        try:
            sns.distplot(results, norm_hist=False, rug=True, ax=ax2)
        except Exception:
            pass
    ax1.set(title='Transition Waveform', xlabel='Time (sec)',
            ylabel='Amplitude (V)')
    ax2.set(title="Risetime Histogram", ylabel="Density",
            xlabel="Risetime (sec)")
    ax2.annotate('Outside Spec: %d / %d\n'
                 'Completed %d%%' % (len(fails), len(results), progress),
                 xy=(0.75, 0.90), xycoords='axes fraction', fontsize=14)
    xlims = ax2.get_xlim()
    ax2.axvspan(failure_criteria, xlims[1] - 0.001 * (xlims[1] - xlims[0]),
                alpha=0.1, color='red')
    plt.pause(0.01)
//  [python]
def phase1_plot_update(f, ax1, ax2, data, passed, results, fails,
                       failure_criteria, progress):
    ax1.cla()
    ax2.cla()
    sns.lineplot(x=data.time, y=data.ch1, color="g" if passed else "r",
               ax=ax1)
    if len(results) > 1:
        try:
            sns.distplot(results, norm_hist=False, rug=True, ax=ax2)
        except Exception:
            pass
    ax1.set(title='Transition Waveform', xlabel='Time (sec)',
            ylabel='Amplitude (V)')
    ax2.set(title="Risetime Histogram", ylabel="Density",
            xlabel="Risetime (sec)")
    ax2.annotate('Outside Spec: %d / %d\n'
                 'Completed %d%%' % (len(fails), len(results), progress),
                 xy=(0.75, 0.90), xycoords='axes fraction', fontsize=14)
    xlims = ax2.get_xlim()
    ax2.axvspan(failure_criteria, xlims[1] - 0.001 * (xlims[1] - xlims[0]),
                alpha=0.1, color='red')
    plt.pause(0.01)
//  [python]
def plot_data(data, xaxis, value, condition, smooth=1, **kwargs):
    if smooth > 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", rc=params)

    sns.tsplot(
        data=data,
        time=xaxis,
        value=value,
        unit="Unit",
        condition=condition,
        ci="sd",
        linewidth=0.75,
        **kwargs,
    )

    plt.rcParams.update(params)
    plt.legend(
        handlelength=1,
        handleheight=0.0,
        bbox_to_anchor=(0.5, 1.125),
        loc="upper center",
        ncol=6,
        columnspacing=0.9,
    ).set_draggable(True)

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
//  [python]
def plot_data(data, xaxis, value, condition, smooth=1, **kwargs):
    if smooth > 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", rc=params)

    sns.lineplot(
        data=data,
        x=xaxis,
        y=value,
        hue=condition,
        ci="sd",
        linewidth=0.75,
        **kwargs,
    )

    plt.rcParams.update(params)
    plt.legend(
        handlelength=1,
        handleheight=0.0,
        bbox_to_anchor=(0.5, 1.125),
        loc="upper center",
        ncol=6,
        columnspacing=0.9,
    ).set_draggable(True)

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
//  [python]
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
//  [python]
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.lineplot(data=full_data, x="Episode", y="Average Episode Reward", hue='Benchmark', ax=ax, ci=[68, 95], palette=self.palette)

        return plot
//  [python]
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
//  [python]
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.lineplot(data=full_data, x="Time step", y="Average Episode Reward", hue='Benchmark', ax=ax, ci=[68, 95], palette=self.palette)

        return plot
//  [python]
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
//  [python]
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.lineplot(data=full_data, x="Second", y="Average Episode Reward", hue='Benchmark', ax=ax, ci=[68, 95], palette=self.palette)

        return plot
//  [python]
def plot(datasets, x_label, y_label, condition, smooth, lineloc=None, linename=None):
    """
        plot datasets to figure
    """
    # initiate plot
    plt.figure()

    # smooth
    if smooth > 1:
        # smooth done by taking nearby averages
        smooth = min(smooth, len(datasets[0]))
        y = np.ones(smooth)
        for dataset in datasets:
            x = np.asarray(dataset[y_label])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            dataset[y_label] = smoothed_x

    # merge multiple datasets into one for 'lineplot'
    # each dataset differentiated by condition
    datasets = pd.concat(datasets, ignore_index=True)


    # Graphics
    # plot data curves
    #sns.lineplot(data=datasets, x=x_label, y=y_label, hue=condition, ci='sd')
    sns.tsplot(data=datasets, time=x_label, value=y_label, unit="Unit", condition=condition, ci='sd')

    # plot straight lines
    if lineloc is not None:
        for i in range(len(lineloc)):
            plt.axhline(y=lineloc[i], linestyle=STYLE[i], label=linename[i], color=LINECOLOR, linewidth=LINEWIDTH[i])

    # Texts
    # other attributes: family='serif'  style='italic'  etc  fontsize='X-large' fontsize=20
    plt.legend(loc='best', title=None, frameon=True, fontsize='medium')
    plt.xlabel(x_label, labelpad=5, fontsize='large')
    plt.ylabel(y_label, labelpad=5, fontsize='large')
    plt.title(None)

    # Layout
    #plt.ylim(0,18)
    plt.tight_layout(pad=1)
    #.savefig("data/figures/"+y_label+".png")

    # show plot
    plt.show()
//  [python]
def plot(datasets, x_label, y_label, condition, smooth, lineloc=None, linename=None):
    """
        plot datasets to figure
    """
    # initiate plot
    plt.figure()

    # smooth
    if smooth > 1:
        # smooth done by taking nearby averages
        smooth = min(smooth, len(datasets[0]))
        y = np.ones(smooth)
        for dataset in datasets:
            x = np.asarray(dataset[y_label])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            dataset[y_label] = smoothed_x

    # merge multiple datasets into one for 'lineplot'
    # each dataset differentiated by condition
    datasets = pd.concat(datasets, ignore_index=True)


    # Graphics
    # plot data curves
    sns.lineplot(data=datasets, x=x_label, y=y_label, hue=condition, ci='sd')
    #sns.tsplot(data=datasets, time=x_label, value=y_label, unit="Unit", condition=condition, ci='sd')

    # plot straight lines
    if lineloc is not None:
        for i in range(len(lineloc)):
            plt.axhline(y=lineloc[i], linestyle=STYLE[i], label=linename[i], color=LINECOLOR, linewidth=LINEWIDTH[i])

    # Texts
    # other attributes: family='serif'  style='italic'  etc  fontsize='X-large' fontsize=20
    plt.legend(loc='best', title=None, frameon=True, fontsize='medium')
    plt.xlabel(x_label, labelpad=5, fontsize='large')
    plt.ylabel(y_label, labelpad=5, fontsize='large')
    plt.title(None)

    # Layout
    #plt.ylim(0,18)
    plt.tight_layout(pad=1)
    #.savefig("data/figures/"+y_label+".png")

    # show plot
    plt.show()
//  [python]
sns.set(style="darkgrid")

# Load the long-form example gammas dataset
gammas = sns.load_dataset("gammas")

# Plot the response with standard error
sns.tsplot(data=gammas, time="timepoint", unit="subject",
           condition="ROI", value="BOLD signal")
//  [python]
sns.set(style="darkgrid")

# Load the long-form example gammas dataset
gammas = sns.load_dataset("gammas")

# Plot the response with standard error
sns.lineplot(data=gammas, x="timepoint", y="BOLD signal", hue="ROI", ci="sd", units="subject")
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, no_legend=False,
              legend_loc='best', color=None, linestyle=None, font_scale=1.5,
              label_font_size=24, xlabel=None, ylabel=None,
              **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=font_scale)
    # sns.set_palette('bright')

    ax = sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, legend=(not no_legend), ci='sd',
               n_boot=0, color=color)
    if linestyle is not None:
        for i in range(len(linestyle)):
            ax.lines[i].set_linestyle(linestyle[i])

    xlabel = 'environment interactions' if xlabel is None else xlabel
    ylabel = 'average test return' if ylabel is None else ylabel
    plt.xlabel(xlabel, fontsize=label_font_size)
    plt.ylabel(ylabel, fontsize=label_font_size)

    """
    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.
    """
    if not no_legend:
        plt.legend(loc=legend_loc, fontsize=label_font_size)

    """
    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)
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, no_legend=False,
              legend_loc='best', color=None, linestyle=None, font_scale=1.5,
              label_font_size=24, xlabel=None, ylabel=None,
              **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=font_scale)
    # sns.set_palette('bright')

    ax = sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
    if linestyle is not None:
        for i in range(len(linestyle)):
            ax.lines[i].set_linestyle(linestyle[i])

    xlabel = 'environment interactions' if xlabel is None else xlabel
    ylabel = 'average test return' if ylabel is None else ylabel
    plt.xlabel(xlabel, fontsize=label_font_size)
    plt.ylabel(ylabel, fontsize=label_font_size)

    if not no_legend:
        plt.legend(loc=legend_loc, fontsize=label_font_size)

    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)
//  [python]
def plot_seaborn(data):
  for i, row in enumerate(data):
    y_range = np.max(row) - np.min(row)
    data[i+1:] += y_range

  seaborn.tsplot(data=data)
//  [python]
def plot_seaborn(data):
  for i, row in enumerate(data):
    y_range = np.max(row) - np.min(row)
    data[i+1:] += y_range

  seaborn.lineplot(data=data)
//  [python]
def drawing_CP(plt, algorithm, number, color, label):
    reward, len = get_data(algorithm=algorithm, env_index=0, number=number)
    sns.tsplot(time=np.arange(len), data=reward, color=color, linestyle='-')  # color=darkorange dodgerblue
    plt.plot(reward.mean(0), color=color, label=label)
    plt.title("CartPole-v1", size=14)
    plt.xlabel("Steps", size=14)
    plt.ylabel("Reward", size=14)
    plt.xticks([0, 50, 100, 150], ['0', '50k', '100k', '150k'], size=14)
    plt.yticks(size=14)
    plt.ylim([0, 510])
    plt.legend(loc='lower right', fontsize=14)
//  [python]
def drawing_CP(plt, algorithm, number, color, label):
    reward, len = get_data(algorithm=algorithm, env_index=0, number=number)
    sns.lineplot(x=np.arange(len), y=reward, color=color, linestyle='-')  # color=darkorange dodgerblue
    plt.plot(reward.mean(0), color=color, label=label)
    plt.title("CartPole-v1", size=14)
    plt.xlabel("Steps", size=14)
    plt.ylabel("Reward", size=14)
    plt.xticks([0, 50, 100, 150], ['0', '50k', '100k', '150k'], size=14)
    plt.yticks(size=14)
    plt.ylim([0, 510])
    plt.legend(loc='lower right', fontsize=14)
//  [python]
def plot_imp_ts(I_ts):
    sns.plt.figure()
    ax = sns.tsplot(data=I_ts, time="Term", unit="Model", condition="Feature",
                    value="Importance")
    ax.figure.show()
    return ax
//  [python]
def plot_imp_ts(I_ts):
    sns.plt.figure()
    ax = sns.lineplot(data=I_ts, x="Term", y="Importance", hue="Feature", units="Model")
    ax.figure.show()
    return ax
//  [python]
def drawing_LL(plt, algorithm, number, color, label):
    reward, len = get_data(algorithm=algorithm, env_index=1, number=number)
    sns.tsplot(time=np.arange(len), data=reward, color=color, linestyle='-')  # color=darkorange dodgerblue
    plt.plot(reward.mean(0), color=color, label=label)
    plt.title("LunarLander-v2", size=14)
    plt.xlabel("Steps", size=14)
    plt.ylabel("Reward", size=14)
    plt.xticks([0, 100, 200, 300, 400], ['0', '100k', '200k', '300k', '400k'], size=14)
    plt.yticks(size=14)
    plt.ylim([-300, 300])
    plt.legend(loc='lower right', fontsize=14)
//  [python]
def drawing_LL(plt, algorithm, number, color, label):
    reward, len = get_data(algorithm=algorithm, env_index=1, number=number)
    sns.lineplot(x=np.arange(len), y=reward, color=color, linestyle='-')
    plt.plot(reward.mean(0), color=color, label=label)
    plt.title("LunarLander-v2", size=14)
    plt.xlabel("Steps", size=14)
    plt.ylabel("Reward", size=14)
    plt.xticks([0, 100, 200, 300, 400], ['0', '100k', '200k', '300k', '400k'], size=14)
    plt.yticks(size=14)
    plt.ylim([-300, 300])
    plt.legend(loc='lower right', fontsize=14)
//  [python]
def plot_sine_learning(models, fits=(0, 1), lr=0.01, marker='s', linestyle='--', SINE_TEST=None):
    data = {'model': [], 'fits': [], 'loss': [], 'set': []}
    for name, models in models:
        if not isinstance(models, list):
            models = [models]
        for n_model, model in enumerate(models):
            for n_test, test in enumerate(SINE_TEST):
                n_test = n_model * len(SINE_TEST) + n_test
                fit_res = eval_sine_test(model, test, fits, lr)
                for n, _, loss in fit_res:
                    data['model'].append(name)
                    data['fits'].append(n)
                    data['loss'].append(loss)
                    data['set'].append(n_test)

    ax = sbs.tsplot(
        pd.DataFrame(data), condition='model', value='loss',
        time='fits', unit='set', marker=marker, linestyle=linestyle)
    plt.show()
//  [python]
def plot_sine_learning(models, fits=(0, 1), lr=0.01, marker='s', linestyle='--', SINE_TEST=None):
    data = {'model': [], 'fits': [], 'loss': [], 'set': []}
    for name, models in models:
        if not isinstance(models, list):
            models = [models]
        for n_model, model in enumerate(models):
            for n_test, test in enumerate(SINE_TEST):
                n_test = n_model * len(SINE_TEST) + n_test
                fit_res = eval_sine_test(model, test, fits, lr)
                for n, _, loss in fit_res:
                    data['model'].append(name)
                    data['fits'].append(n)
                    data['loss'].append(loss)
                    data['set'].append(n_test)

    ax = sns.lineplot(
        data=pd.DataFrame(data), x='fits', y='loss',
        hue='model', units='set', estimator=None, marker=marker, linestyle=linestyle)
    plt.show()
//  [python]
def graph():
    # centralbank = pd.read_csv('aggregate_centralbank.csv').ix[20:]
    firm = pd.read_csv('aggregate_firm.csv').ix[400:600]
    hh = pd.read_csv('aggregate_household.csv').ix[400:600]

    fig, ax = plt.subplots(nrows=3, ncols=3)

    ax[0][0].set_title('money / dead (red)')
    ax2 = ax[0][0].twinx()
    sb.tsplot(data=firm['dead'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[0][0], color='r')

    ax[0][1].set_title('price (mean) / money (red)')
    ax2 = ax[0][1].twinx()
    sb.tsplot(data=firm['price_mean'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[0][1], color='r')

    ax[1][1].set_title('produced')
    ax2 = ax[1][1].twinx()
    sb.tsplot(data=firm['produced'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[1][1], color='r')

    ax[1][0].set_title('price_std')
    ax2 = ax[1][0].twinx()
    sb.tsplot(data=firm['price_std'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[1][0], color='r')

    ax[2][0].set_title('price coef of variation')
    ax2 = ax[2][0].twinx()
    sb.tsplot(data=firm['price_std'] / firm['price_mean'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[2][0], color='r')

    ax[2][1].set_title('inventory_change')
    ax2 = ax[2][1].twinx()
    sb.tsplot(data=firm['inventory'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[2][1], color='r')

    ax[0][2].set_title('household money / firm money')
    ax2 = ax[0][2].twinx()
    sb.tsplot(data=hh['money'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[0][2], color='r')

    ax[1][2].set_title('firm rationing / firm money')
    ax2 = ax[1][2].twinx()
    sb.tsplot(data=firm['rationing_mean'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[1][2], color='r')

    ax[2][2].set_title('hh rationing / firm money')
    ax2 = ax[2][2].twinx()
    sb.tsplot(data=hh['rationing_mean'], ax=ax2)
    sb.tsplot(data=firm['money'], ax=ax[2][2], color='r')


    try:
        firm = pd.read_csv('panel_firm.csv')[200:]
        print(ggplot(aes('round', 'price'), data=firm[firm['id'] < 100]) + geom_line() + facet_wrap('id'))
        print(ggplot(aes('round', 'price'), data=firm[firm['id'] > 100]) + geom_line() + facet_wrap('id'))
    except IOError:
        pass

    try:
        sb.plt.savefig('/Users/taghawi/Desktop/foo.png', bbox_inches='tight', dpi=300)
    except IOError:
        pass
    try:
        sb.plt.savefig('/home/taghawi/Desktop/foo.png', bbox_inches='tight', dpi=300)
    except IOError:
        pass
    sb.plt.show()
//  [python]
def graph():
    # centralbank = pd.read_csv('aggregate_centralbank.csv').ix[20:]
    firm = pd.read_csv('aggregate_firm.csv').ix[400:600]
    hh = pd.read_csv('aggregate_household.csv').ix[400:600]

    fig, ax = plt.subplots(nrows=3, ncols=3)

    ax[0][0].set_title('money / dead (red)')
    ax2 = ax[0][0].twinx()
    sb.lineplot(data=firm, x=firm.index, y='dead', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[0][0], color='r')

    ax[0][1].set_title('price (mean) / money (red)')
    ax2 = ax[0][1].twinx()
    sb.lineplot(data=firm, x=firm.index, y='price_mean', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[0][1], color='r')

    ax[1][1].set_title('produced')
    ax2 = ax[1][1].twinx()
    sb.lineplot(data=firm, x=firm.index, y='produced', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[1][1], color='r')

    ax[1][0].set_title('price_std')
    ax2 = ax[1][0].twinx()
    sb.lineplot(data=firm, x=firm.index, y='price_std', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[1][0], color='r')

    ax[2][0].set_title('price coef of variation')
    ax2 = ax[2][0].twinx()
    sb.lineplot(data=firm, x=firm.index, y=(firm['price_std'] / firm['price_mean']), ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[2][0], color='r')

    ax[2][1].set_title('inventory_change')
    ax2 = ax[2][1].twinx()
    sb.lineplot(data=firm, x=firm.index, y='inventory', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[2][1], color='r')

    ax[0][2].set_title('household money / firm money')
    ax2 = ax[0][2].twinx()
    sb.lineplot(data=hh, x=hh.index, y='money', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[0][2], color='r')

    ax[1][2].set_title('firm rationing / firm money')
    ax2 = ax[1][2].twinx()
    sb.lineplot(data=firm, x=firm.index, y='rationing_mean', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[1][2], color='r')

    ax[2][2].set_title('hh rationing / firm money')
    ax2 = ax[2][2].twinx()
    sb.lineplot(data=hh, x=hh.index, y='rationing_mean', ax=ax2)
    sb.lineplot(data=firm, x=firm.index, y='money', ax=ax[2][2], color='r')


    try:
        firm = pd.read_csv('panel_firm.csv')[200:]
        print(ggplot(aes('round', 'price'), data=firm[firm['id'] < 100]) + geom_line() + facet_wrap('id'))
        print(ggplot(aes('round', 'price'), data=firm[firm['id'] > 100]) + geom_line() + facet_wrap('id'))
    except IOError:
        pass

    try:
        sb.plt.savefig('/Users/taghawi/Desktop/foo.png', bbox_inches='tight', dpi=300)
    except IOError:
        pass
    try:
        sb.plt.savefig('/home/taghawi/Desktop/foo.png', bbox_inches='tight', dpi=300)
    except IOError:
        pass
    sb.plt.show()
//  [python]
def graph_ts(ts):
    for k in ts.target.unique():
        fig, axes = plt.subplots(figsize=(15,5))
        sns.tsplot(ts[ts.target == k], time='time', unit='id', condition='target', value='value', err_style='unit_traces', ax=axes)    
    fig, axes = plt.subplots(figsize=(15,5))
    sns.tsplot(ts, time='time', unit='id', condition='target', value='value', err_style='unit_traces', ax=axes)
    return None
//  [python]
def graph_ts(ts):
    for k in ts.target.unique():
        fig, axes = plt.subplots(figsize=(15,5))
        sns.lineplot(data=ts[ts.target == k], x='time', y='value', hue='target', units='id', estimator=None, lw=1, ax=axes)    
    fig, axes = plt.subplots(figsize=(15,5))
    sns.lineplot(data=ts, x='time', y='value', hue='target', units='id', estimator=None, lw=1, ax=axes)
    return None
//  [python]
def subplot_data(data, ax, value="mean", title=None, min_score=None, max_score=None):
    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    if min_score is not None and max_score is not None:
        scale = float(max_score) - float(min_score)
        data[value] = (data[value] - float(min_score))/scale
        min_data = np.min(data[value])
        max_data = np.max(data[value])
        min_data_q = np.round(min_data / 0.2)*0.2
        max_data_q = np.round(max_data / 0.2)*0.2
    sns.tsplot(data=data, time="Iteration", value=value, unit="Unit", condition="Condition", ax=ax)
    ax.set_xlabel(None)
    ax.set_ylabel(None)
    if title is not None:
        plt.title(title)
    if min_score is not None and max_score is not None:
        ax.set_yticks(np.arange(min_data_q, max_data_q+0.2, 0.2))
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.get_legend().remove()
    return ax