Python matplotlib.pyplot.savefig() Examples

The following are code examples for showing how to use matplotlib.pyplot.savefig(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: wikilinks   Author: trovdimi   File: normalized_entropy.py    MIT License 6 votes vote down vote up
def plot_entropy_distribution():
    fig = plt.figure()
    ax = fig.add_subplot(111)

    entropy = read_pickle('output/normalized_entropy.obj')

    hist, bin_edges = np.histogram(entropy, bins=10000)
    print hist, bin_edges

    #ax.set_yscale('log')
    #ax.set_xscale('log')
    ax.plot(bin_edges[:-1], hist, marker='o', markersize=3, markeredgecolor='none', color='#D65F5F')

    #ax.set_ylim([10**0, 10**6])
    #ax.set_xlim([10**0, 10**6])
    ax.set_xlabel('Entropy')
    ax.set_ylabel('Frequency')

    fig.tight_layout()
    fig.savefig( 'output/normalized_entropy_distribution.pdf', bbox_inches='tight') 
Example 2
Project: wikilinks   Author: trovdimi   File: normalized_entropy.py    MIT License 6 votes vote down vote up
def plot_entropy_hist():
    fig = plt.figure()
    ax = fig.add_subplot(111)

    entropy = read_pickle('output/normalized_entropy.obj')
    number_of_zeros = [1 if item is 0 else 0 for item in entropy]

    print len(number_of_zeros)
    print sum(number_of_zeros)
    n, bins, patches = ax.hist(entropy, 50)
    ax.plot(bins, )
    #ax.set_ylim([-1,1])
    ax.set_xlim([0,1])
    ax.set_yscale('log')
    ax.set_xlabel('Normalized entropy')
    ax.set_ylabel('Frequency (log)')

    fig.tight_layout()
    fig.savefig( 'output/normalized_entropy_hist.pdf', bbox_inches='tight') 
Example 3
Project: wikilinks   Author: trovdimi   File: normalized_entropy.py    MIT License 6 votes vote down vote up
def plot_gini_hist(name):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    gini = read_pickle('output/'+name+'.obj')
    number_of_zeros = [1 if item is 0 else 0 for item in gini]

    print len(number_of_zeros)
    print sum(number_of_zeros)
    #n, bins, patches = ax.hist(gini, 50,  color='#D65F5F', edgecolor='none')
    n, bins, patches = ax.hist(gini, 50,  edgecolor='none')
    ax.plot(bins)
    #ax.set_ylim([-1,1])
    ax.set_xlim([0,1])
    #ax.set_yscale('log')
    ax.set_xlabel('Gini coefficient')
    ax.set_ylabel('Frequency')

    fig.tight_layout()
    fig.savefig( 'output/'+name+'.pdf', bbox_inches='tight') 
Example 4
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 votes vote down vote up
def _plot_old_pred_data(old_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, algorithm_str, minutes_str):
    actual_bg_array = old_pred_data.result_actual_bg_array
    actual_bg_time_array = old_pred_data.result_actual_bg_time_array
    pred_array = old_pred_data.result_pred_array
    pred_time_array = old_pred_data.result_pred_time_array

    #Root mean squared error
    rms = math.sqrt(metrics.mean_squared_error(actual_bg_array, pred_array))
    print "                Root Mean Squared Error: " + str(rms)
    print "                Mean Absolute Error: " + str(metrics.mean_absolute_error(actual_bg_array, pred_array))
    print "                R^2 Coefficient of Determination: " + str(metrics.r2_score(actual_bg_array, pred_array))

    plot, zone = ClarkeErrorGrid.clarke_error_grid(actual_bg_array, pred_array, id_str + " " + algorithm_str + " " + minutes_str)
    print "                Percent A:{}".format(float(zone[0]) / (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Percent C, D, E:{}".format(float(zone[2] + zone[3] + zone[4])/ (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Zones are A:{}, B:{}, C:{}, D:{}, E:{}\n".format(zone[0],zone[1],zone[2],zone[3],zone[4])
    if save_clarke_plot: plt.savefig(id_str + algorithm_str.replace(" ", "") + minutes_str + "clarke.png")
    if show_clarke_plot: plot.show()

    plt.clf()
    plt.plot(actual_bg_time_array, actual_bg_array, label="Actual BG", color='black', linestyle='-')
    plt.plot(pred_time_array, pred_array, label="BG Prediction", color='black', linestyle=':')
    plt.title(id_str + " " + algorithm_str + " " + minutes_str + " BG Analysis")
    plt.ylabel("Blood Glucose Level (mg/dl)")
    plt.xlabel("Time (minutes)")
    plt.legend(loc='upper left')

    # SHOW/SAVE PLOT DEPENDING ON THE BOOLEAN PARAMETER
    if save_pred_plot: plt.savefig(id_str + algorithm_str.replace(" ","") + minutes_str + "plot.png")
    if show_pred_plot: plt.show()


#Function to analyze the old OpenAPS data 
Example 5
Project: cloudlog   Author: navoshta   File: cloudlog.py    MIT License 6 votes vote down vote up
def add_plot(self, notify=False, caption=None):
        """
        Saves current `pyplot` plot as a .png, uploads it to Dropbox and optionally notifies via Telegram chat.

        Parameters
        ----------
        notify  :
                  Flag indicating if we need to send a Telegram notification.
        caption :
                  Optional plot caption.
        """
        plot_file = time.strftime('%Y-%m-%d_%H-%M-%S') + '.png'
        plot_path = os.path.join(self.root, plot_file)
        pyplot.savefig(plot_path)

        self.cloud_upload_plot(plot_file)
        if notify:
            self.bot_send_plot(plot_file, caption) 
Example 6
Project: dc_tts   Author: Kyubyong   File: utils.py    Apache License 2.0 6 votes vote down vote up
def plot_alignment(alignment, gs, dir=hp.logdir):
    """Plots the alignment.

    Args:
      alignment: A numpy array with shape of (encoder_steps, decoder_steps)
      gs: (int) global step.
      dir: Output path.
    """
    if not os.path.exists(dir): os.mkdir(dir)

    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png')
    plt.close(fig) 
Example 7
Project: tensorflow-DeepFM   Author: ChenglongChen   File: main.py    MIT License 6 votes vote down vote up
def _plot_fig(train_results, valid_results, model_name):
    colors = ["red", "blue", "green"]
    xs = np.arange(1, train_results.shape[1]+1)
    plt.figure()
    legends = []
    for i in range(train_results.shape[0]):
        plt.plot(xs, train_results[i], color=colors[i], linestyle="solid", marker="o")
        plt.plot(xs, valid_results[i], color=colors[i], linestyle="dashed", marker="o")
        legends.append("train-%d"%(i+1))
        legends.append("valid-%d"%(i+1))
    plt.xlabel("Epoch")
    plt.ylabel("Normalized Gini")
    plt.title("%s"%model_name)
    plt.legend(legends)
    plt.savefig("./fig/%s.png"%model_name)
    plt.close()


# load data 
Example 8
Project: synthetic-data-tutorial   Author: theodi   File: ModelInspector.py    MIT License 6 votes vote down vote up
def mutual_information_heatmap(self, figure_filepath, attributes: List = None):
        if attributes:
            private_df = self.private_df[attributes]
            synthetic_df = self.synthetic_df[attributes]
        else:
            private_df = self.private_df
            synthetic_df = self.synthetic_df

        private_mi = pairwise_attributes_mutual_information(private_df)
        synthetic_mi = pairwise_attributes_mutual_information(synthetic_df)

        fig = plt.figure(figsize=(15, 6), dpi=120)
        fig.suptitle('Pairwise Mutual Information Comparison (Private vs Synthetic)', fontsize=20)
        ax1 = fig.add_subplot(121)
        ax2 = fig.add_subplot(122)
        sns.heatmap(private_mi, ax=ax1, cmap="GnBu")
        sns.heatmap(synthetic_mi, ax=ax2, cmap="GnBu")
        ax1.set_title('Private, max=1', fontsize=15)
        ax2.set_title('Synthetic, max=1', fontsize=15)
        fig.autofmt_xdate()
        fig.tight_layout()
        plt.subplots_adjust(top=0.83)

        plt.savefig(figure_filepath, bbox_inches='tight')
        plt.close() 
Example 9
Project: ortholotree   Author: oxpeter   File: internal.py    GNU General Public License v2.0 6 votes vote down vote up
def rank_scores(homologlist, thresh1=0, thresh2=None, genename=None, outfile=None, showplot=False):
    yvalues = sorted([val[1] for val in homologlist.values()], reverse=True)
    plt.plot(yvalues)
    score_cutoff = thresh1 * max(yvalues)
    sample_cutoff = sum(1 for s in yvalues if s >= thresh1 * max(yvalues))
    plt.axhline( score_cutoff , color='r' )
    if thresh2:
        plt.axhline( thresh2 * max(yvalues) , color='r' )
    plt.axvline( sample_cutoff -1 , color='g' )
    plt.text(sample_cutoff + 1,score_cutoff + 10 , "(%d,%d)" % (sample_cutoff,score_cutoff) )
    plt.xlabel("Gene rank")
    plt.ylabel("Phmmer score")
    plt.title("Ranking of phmmer scores for alignment with %s" % genename)
    if outfile:
        plt.savefig(outfile, format='png')
    if showplot:
        plt.show()
    else:
        plt.close() 
Example 10
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def vis_performance(gather_prec,gather_recal,path,asd='[email protected]',vtype='nfrac'):
    fig = plt.figure()      
    plt.plot(gather_recal.index, gather_recal.mean(axis=1),marker='o')
    plt.plot(gather_prec.index, gather_prec.mean(axis=1),marker='^')

    plt.errorbar(gather_recal.index, gather_recal.mean(axis=1), gather_recal.std(axis=1), linestyle='None')
    plt.errorbar(gather_prec.index, gather_prec.mean(axis=1), gather_prec.std(axis=1), linestyle='None')
    
    if vtype=='nfrac':
        plt.title('Precision and recall under different noise fractions')
        plt.xlabel('Noise fraction (percentile)')
        plt.ylim(-0.05,1.1)
        plt.yticks(np.arange(0,1.2,0.2))
        plt.legend(['Recall','Precision'],loc=0)
        plt.savefig(path+'gathered_dnoise_performance_nfrac_'+asd+'.pdf') 
    elif vtype=='astd':
        plt.title('Precision and recall under different prior SD')
        plt.xlabel('Prior standard deviation of discrimination')
        plt.xlim(0.5,3.25)
        plt.ylim(-0.05,1.1)
        plt.yticks(np.arange(0,1.2,0.2))
        plt.legend(['Recall','Precision'],loc=0)
        plt.savefig(path+'gathered_dnoise_performance_asd_nfrac20.pdf')
    plt.close(fig) 
Example 11
Project: didi_competition   Author: Heipiao   File: plot_traffic_data.py    MIT License 6 votes vote down vote up
def plot_single_day_traffic(df):
    y_tj_l1 = df["tj_level1_count"]
    y_tj_l2 = df["tj_level2_count"]
    y_tj_l3 = df["tj_level3_count"]
    y_tj_l4 = df["tj_level4_count"]

    x_time = df["time"]
    x_district = df["district"]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(x_time, x_district, y_tj_l1, )
    #ax.plot_surface(x_time, x_district, y_tj_l1)
    print(plt.get_backend())
    plt.show()
    plt.savefig("plot_traffic.png") 
Example 12
Project: cs294-112_hws   Author: xuwd11   File: plot_part1.py    MIT License 6 votes vote down vote up
def plot_13(data):
    r1, r2, r3, r4 = data
    plt.figure()
    add_plot(r3, 'MeanReward100Episodes');
    add_plot(r3, 'BestMeanReward', 'gamma = 0.9');
    add_plot(r2, 'MeanReward100Episodes');
    add_plot(r2, 'BestMeanReward', 'gamma = 0.99');
    add_plot(r4, 'MeanReward100Episodes');
    add_plot(r4, 'BestMeanReward', 'gamma = 0.999');
    plt.legend();
    plt.xlabel('Time step');
    plt.ylabel('Reward');
    plt.savefig(
        os.path.join('results', 'p13.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 13
Project: cs294-112_hws   Author: xuwd11   File: plot_3.py    MIT License 6 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('logdir', type=str)
    parser.add_argument('--save_name', type=str, default='results')
    args = parser.parse_args()
    
    if not os.path.exists('results'):
        os.makedirs('results')
    
    plot_3(get_datasets(args.logdir))
    
    plt.savefig(
        os.path.join('results', args.save_name + '.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 14
Project: multi-dimensional-topic-model   Author: LaoWang-Lab   File: plot.py    MIT License 6 votes vote down vote up
def plot_fig(json_file, save_fig=False):
    with open(json_file) as f:
        data = json.load(f)
    H, E, M, wot, iter = data['H'], data['E'], data['M'], data['wot'], data['iter']
    fig, axs = plt.subplots(E, H, figsize=(2.5 * E, 3.5 *H), sharex=True)
    fig.suptitle('H:%d E:%d M:%d wot:%d iter:%d' % (H, E, M, wot, iter), fontsize=20, fontweight='bold')
    n_het = np.array(data['topic'])
    y_limits_max = 1.05 * n_het.sum() / (E * H * wot)
    x = np.arange(data['T'])
    for e in range(data['E']):
        for h in range(data['H']):
            # print(len(x), np.shape(n_het), np.shape(axs))
            sns.barplot(x, n_het[h,e,:], palette="Set3", ax=axs[e][h])
            axs[e][h].set_ylabel("counts")
            axs[e][h].set_title("h:%d e:%d" % (h,e))
            axs[e][h].set_ylim([0, y_limits_max])
    plt.tight_layout()
    fig.subplots_adjust(top=0.9)
    if save_fig:
        i = data['iter']
        plt.savefig('%s/iter%03d.png' % (os.path.dirname(json_file), i), dpi=72, format='png')
    else:
        plt.show()
    plt.close() 
Example 15
Project: trunklucator   Author: Dumbris   File: plot_perf.py    Apache License 2.0 6 votes vote down vote up
def plot_performance(performance_history):
    fig, ax = plt.subplots(figsize=(8.5, 6), dpi=130)

    ax.plot(performance_history)
    ax.scatter(range(len(performance_history)), performance_history, s=13)

    ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=5, integer=True))
    ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=10))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(xmax=1))

    ax.set_ylim(bottom=0, top=1)
    ax.grid(True)

    ax.set_title('Incremental classification accuracy')
    ax.set_xlabel('Query iteration')
    ax.set_ylabel('Classification Accuracy')

    image = BytesIO()
    plt.plot()
    plt.savefig(image, format='png')
    plt.cla()
    plt.close(fig)
    return ''' <img src="data:image/png;base64,{}" border="0" /> '''.format(base64.encodebytes(image.getvalue()).decode()) 
Example 16
Project: Recipes   Author: Lasagne   File: massachusetts_road_segm.py    MIT License 6 votes vote down vote up
def plot_some_results(pred_fn, test_generator, n_images=10):
    fig_ctr = 0
    for data, seg in test_generator:
        res = pred_fn(data)
        for d, s, r in zip(data, seg, res):
            plt.figure(figsize=(12, 6))
            plt.subplot(1, 3, 1)
            plt.imshow(d.transpose(1,2,0))
            plt.title("input patch")
            plt.subplot(1, 3, 2)
            plt.imshow(s[0])
            plt.title("ground truth")
            plt.subplot(1, 3, 3)
            plt.imshow(r)
            plt.title("segmentation")
            plt.savefig("road_segmentation_result_%03.0f.png"%fig_ctr)
            plt.close()
            fig_ctr += 1
            if fig_ctr > n_images:
                break 
Example 17
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 5 votes vote down vote up
def _plot_initial_windows(self, unsig_base_means, unsig_fcs,
                              sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_windows_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_HexBin_plot")
        plt.savefig("{}/Initial_windows_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 18
Project: PEAKachu   Author: tbischler   File: adaptive.py    ISC License 5 votes vote down vote up
def _plot_initial_peaks(self, unsig_base_means, unsig_fcs,
                            sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_peaks_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_peaks_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_peaks_HexBin_plot")
        plt.savefig("{}/Initial_peaks_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 19
Project: PEAKachu   Author: tbischler   File: consensus_peak.py    ISC License 5 votes vote down vote up
def plot_consensus_peak(self):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._project_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        self._store_peaks()
        comb_cons_value_dict = self._get_peak_coverage()
        df = pd.DataFrame(comb_cons_value_dict, columns=sorted(
            comb_cons_value_dict))
        ax = df.plot(title="Consensus peak per library")
        ax.set_xlabel("Nucleotide position")
        ax.set_ylabel("Relative expression")
        plt.savefig("{}/plots/consensus_peaks.pdf".format(
            self._project_folder)) 
Example 20
Project: wikilinks   Author: trovdimi   File: normalized_entropy.py    MIT License 5 votes vote down vote up
def plot_entropy_ccdf():
    entropy = read_pickle('output/normalized_entropy.obj')


    fig = plt.figure()
    ax = fig.add_subplot(111)


    powerlaw.plot_ccdf(entropy, ax, label='normalized entropy')
    # further plotting
    ax.set_xlabel("Normalized entropy e")
    ax.set_ylabel("Pr(X>=e)")
    plt.legend(fancybox=True, loc='lower left', ncol=1,prop={'size':5})

    plt.tight_layout()
    plt.savefig('output/normalized_entropy_distribution_ccdf.pdf')

    fig = plt.figure()
    ax = fig.add_subplot(111)

    powerlaw.plot_cdf(entropy, ax, label='normalized entropy',color='r')
    # further plotting
    ax.set_xlabel("Normalized entropy e")
    ax.set_ylabel("Pr(X<=e)")
    plt.legend(fancybox=True, loc='lower left', ncol=1,prop={'size':5})

    plt.tight_layout()
    plt.savefig('output/normalized_entropy_distribution_cdf.pdf') 
Example 21
Project: wikilinks   Author: trovdimi   File: normalized_entropy.py    MIT License 5 votes vote down vote up
def plot_entropy_boxplot():
    fig = plt.figure()
    ax = fig.add_subplot(111)

    entropy = read_pickle('output/normalized_entropy.obj')
    ax.boxplot(entropy)

    ax.set_ylim([-1,1])
    #ax.set_xlim([10**0, 10**6])
    ax.set_xlabel('Entropy')
    ax.set_ylabel('Frequency')

    fig.tight_layout()
    fig.savefig( 'output/normalized_entropy_boxplot.pdf', bbox_inches='tight') 
Example 22
Project: Tacotron   Author: ElwynWang   File: signal_process.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_alignment(alignment, gs, mode, path = None):
    """Plots the alignment
    alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)
    gs : (int) global step
    mode: "save_fig" or "with_return". "save_fig":save fig locally, "with_return":return plot for tensorboard
    """

    plt.imshow(alignment, cmap='hot', interpolation='nearest')
    plt.xlabel('Decoder Steps')
    plt.ylabel('Encoder Steps')
    plt.title('{} Steps'.format(gs))

    if mode == "save_fig":
        if path is not None:
            plt.savefig('{}/alignment_{}k.png'.format(path, gs//Hp.save_model_step), format='jpg')
        else:
            print ("Warning! You need specify the saved path! The temporal path is {}".format(Hp.logdir))
            plt.savefig('{}/alignment_{}k.png'.format(Hp.logdir, gs//Hp.save_model_step), format='jpg')

    elif mode == "with_return":
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plot = tf.image.decode_png(buf.getvalue(), channels=4)
        plot = tf.expand_dims(plot,0)
        return plot

    else:
        print ("Error Mode! Exit!")
        sys.exit(0) 
Example 23
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def savefig(fname, dpi=None):
    dpi = 500 if dpi == None else dpi
    plt.savefig(fname, dpi=dpi) 
Example 24
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_plot_from_data(data, name):
    """
    Saves a plot of a given set of data.

    :param data: the data to be plotted
    :param name: the name of the data to be plotted.
    :return: Nothing.
    """

    from algorithm.parameters import params

    # Initialise up figure instance.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot data.
    ax1.plot(data)

    # Set labels.
    ax1.set_ylabel(name, fontsize=14)
    ax1.set_xlabel('Generation', fontsize=14)

    # Plot title.
    plt.title(name)

    # Save plot and close.
    plt.savefig(path.join(params['FILE_PATH'], (name + '.pdf')))
    plt.close() 
Example 25
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_plot_from_file(filename, stat_name):
    """
    Saves a plot of a given stat from the stats file.

    :param filename: a full specified path to a .csv stats file.
    :param stat_name: the stat of interest for plotting.
    :return: Nothing.
    """

    # Read in the data
    data = pd.read_csv(filename, sep="\t")
    try:
        stat = list(data[stat_name])
    except KeyError:
        s = "utilities.stats.save_plots.save_plot_from_file\n" \
            "Error: stat %s does not exist" % stat_name
        raise Exception(s)

        # Set up the figure.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot the data.
    ax1.plot(stat)

    # Plot title.
    plt.title(stat_name)

    # Get save path
    save_path = pathsep.join(filename.split(pathsep)[:-1])

    # Save plot and close.
    plt.savefig(path.join(save_path, (stat_name + '.pdf')))
    plt.close() 
Example 26
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_box_plot(data, names, title):
    """
    Given an array of some data, and a list of names of that data, generate
    and save a box plot of that data.

    :param data: An array of some data to be plotted.
    :param names: A list of names of that data.
    :param title: The title of the plot.
    :return: Nothing
    """

    from algorithm.parameters import params

    import matplotlib.pyplot as plt
    plt.rc('font', family='Times New Roman')

    # Set up the figure.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot tight layout.
    plt.tight_layout()

    # Plot the data.
    ax1.boxplot(np.transpose(data), 1)

    # Plot title.
    plt.title(title)

    # Generate list of numbers for plotting names.
    nums = list(range(len(data))[1:]) + [len(data)]

    # Plot names for each data point.
    plt.xticks(nums, names, rotation='vertical', fontsize=8)

    # Save plot.
    plt.savefig(path.join(params['FILE_PATH'], (title + '.pdf')))

    # Close plot.
    plt.close() 
Example 27
Project: Random-Erasing   Author: zhunzhong07   File: logger.py    Apache License 2.0 5 votes vote down vote up
def savefig(fname, dpi=None):
    dpi = 150 if dpi == None else dpi
    plt.savefig(fname, dpi=dpi) 
Example 28
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: dcgan.py    Apache License 2.0 5 votes vote down vote up
def visual(title, X, name):
    assert len(X.shape) == 4
    X = X.transpose((0, 2, 3, 1))
    X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0, 255).astype(np.uint8)
    n = np.ceil(np.sqrt(X.shape[0]))
    buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
    for i, img in enumerate(X):
        fill_buf(buff, i, img, X.shape[1:3])
    buff = buff[:,:,::-1]
    plt.imshow(buff)
    plt.title(title)
    plt.savefig(name) 
Example 29
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: plot_history.py    Apache License 2.0 5 votes vote down vote up
def plot(self, labels=None, colors=None, y_lim=(0, 1),
             save_path=None, legend_loc='upper right'):
        r"""Update the training history

        Parameters
        ---------
        labels: list of str
            List of label names to plot.
        colors: list of str
            List of line colors.
        save_path: str
            Path to save the plot. Will plot to screen if is None.
        legend_loc: str
            location of legend. upper right by default.
        """
        import matplotlib.pyplot as plt

        if labels is None:
            labels = self.labels
        n = len(labels)

        line_lists = [None]*n
        if colors is None:
            colors = ['C'+str(i) for i in range(n)]
        else:
            assert len(colors) == n

        plt.ylim(y_lim)
        for i, lb in enumerate(labels):
            line_lists[i], = plt.plot(list(range(self.epochs)),
                                      self.history[lb],
                                      colors[i],
                                      label=lb)
        plt.legend(tuple(line_lists), labels, loc=legend_loc)
        if save_path is None:
            plt.show()
        else:
            save_path = os.path.expanduser(save_path)
            plt.savefig(save_path) 
Example 30
Project: GST-Tacotron   Author: KinglittleQ   File: utils.py    MIT License 5 votes vote down vote up
def plot_alignment(alignment, gs):
    """Plots the alignment
    alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)
    gs : (int) global step
    """
    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}k.png'.format(hp.logdir, gs // 1000), format='png') 
Example 31
Project: order   Author: ipudu   File: plot.py    MIT License 5 votes vote down vote up
def plot_ionic(self):
        """plot distribution"""

        data1 = np.loadtxt(self.fprefix+'_'+self.taskname+'_ti.dat')
        data2 = np.loadtxt(self.fprefix+'_'+self.taskname+'_iaafp.dat')

        #plot setting
        #plt.rcParams['font.family'] = 'serif'
        #plt.rcParams['font.serif'] = 'Ubuntu'
        #plt.rcParams['font.monospace'] = 'Ubuntu Mono'
        plt.rcParams['font.size'] = 10
        plt.rcParams['axes.labelsize'] = 10
        #plt.rcParams['axes.labelweight'] = 'bold'
        plt.rcParams['xtick.labelsize'] = 8
        plt.rcParams['ytick.labelsize'] = 8
        plt.rcParams['legend.fontsize'] = 10
        plt.rcParams['figure.titlesize'] = 12

        #clean last plot
        plt.clf()

        plt.xlabel("Simulation time(ps)")
        plt.ylabel("Charge from ions crossing the plane (e)")

        x1 = data1[:,0]
        y1 = data1[:,1]

        x2 = data2[:,0]
        y2 = data2[:,1]


        plt.plot(x1, y1, label='ti')
        plt.plot(x2, y2, label='iaafp')
        plt.legend()
        
        figure = self.fprefix + '_' + self.taskname.upper() + '.pdf'
        plt.savefig(figure, bbox_inches="tight") 
Example 32
Project: ortholotree   Author: oxpeter   File: internal.py    GNU General Public License v2.0 5 votes vote down vote up
def display_alignment(fastafile, conversiondic={}, outfile=None, showplot=True,
                        gapthresh=0.05, domain_prb=None, domain_stats=None):
    fig = build_alignment(fastafile, conversiondic, gapthresh=gapthresh,
                          domain_prb=domain_prb, domain_stats=domain_stats)
    if outfile:
        fig.savefig(outfile, format='png')
    if showplot:
        fig.show()
    else:
        plt.close() 
Example 33
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: PrettyIO.py    GNU General Public License v3.0 5 votes vote down vote up
def print_enrichment_chart(file_handle, vals, title):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print("Error while printing. To use this functionality you need to have matplotlib installed.", file=sys.stderr)
    else:
        fig, ax1 = plt.subplots()
        
        xs = list(range(len(vals)))
        ys =  vals
        
        ax1.plot(xs, ys)
        
        bar_ys = [int(ys[0] > 0)]
        for i in range(1, len(ys)):
            bar_ys.append(int(ys[i] > ys[i - 1]))
        bar_ys = [bar_ys]
        
        pos = ax1.axes.get_position()
        
        ax0 = fig.add_axes([pos.x0, pos.y1, pos.width, 0.1])
        
        ax0.imshow(bar_ys, cmap=plt.cm.Blues, interpolation='nearest')
        ax0.axes.get_yaxis().set_visible(False)
        ax0.axes.get_xaxis().set_visible(False)
        ax0.set_title(title)
        
        plt.savefig(file_handle, bbox_inches=0)
        plt.close() 
Example 34
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def plotMultiple(title,listofResults,smooth):
    '''
    supply lists of precision+recall+name lists
    '''
    fontP = FontProperties()
    fontP.set_size('small')
    num = len(listofResults)
    pal=sns.color_palette("Paired", num)
    colors=pal.as_hex()
    for j,i in enumerate(listofResults):
        linetype = '-'
        if smooth=='Y':
            ax = plt.subplot()
            precision = curveSmooth(i)[0][1:]
            recall = curveSmooth(i)[1][1:]
            ax.plot(recall,precision,linetype,color=colors[j],label=i.method+':\nF=%s C=%s'%(i.opt,i.coverage)) 
            ax.plot(i.recall[int(i.thres*100)],i.precision[int(i.thres*100)],'o',color=colors[j])
        elif smooth=='N':
            ax = plt.subplot()
            ax.plot(i.recall,i.precision,linetype,color=colors[j],label=i.method+':\nF=%s C=%s'%(i.opt,i.coverage))
            ax.plot(i.recall[int(i.thres*100)],i.precision[int(i.thres*100)],'o',color=colors[j])
    plt.axis([0,1,0,1])
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    plt.yticks(numpy.arange(0,1,0.1))
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.title(title)
    figurename = os.path.join('./plots/',title)       
    plt.savefig(figurename,dpi=200)
    plt.close() 
Example 35
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def actual_categorical_plot(group, stat, keys, values):
    name = stat + " " + group
    plt.clf()
    plt.bar(range(len(keys)), values)
    plt.xticks(range(len(keys)), keys)
    plt.title(name)
    plt.savefig(PLOT_PATH + "/" + name+".png")
    plt.clf() 
Example 36
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def timeline_plot(group, stat, keys, values, fig=None):
    """
    If fig is None, plot in a new figure
    If fig is not None, use the group as label and plot in that figure
    """
    def prepare(int_keys, values):
        # add 0 where keys are missing
        values = dict(zip(int_keys, values))
        keys = list(range(max(int_keys))) # add missing dates
        values = [values.get(i, 0) for i in keys] # add zero as value for the missing dates
        # prepare plotting as well
        locs = keys[::int(len(keys)/6)]
        dates = [get_str_date(i) for i in locs]
        return keys, values, locs, dates
    
    if fig is None:
        plt.clf()
        name = stat + " " + group
        keys, values, locs, dates = prepare(keys, values)
        plt.plot(keys, values)
        plt.xticks(locs, dates)
        plt.title(name)
        plt.savefig(PLOT_PATH + "/" + name+".png")
        plt.clf()
    else:
        keys, values, locs, dates = prepare(keys, values)
        plt.plot(keys, values, label=group)
        plt.xticks(locs, dates)



# -----
# Groups (combos from group_by and plots)
# ----- 
Example 37
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def plot(self, stat_name, keys, values):
        plt.clf()
        fig = plt.figure()

        cats = list(dict(keys).keys()) # keys are cat, time pairs
        for cat in cats:
            filtered_values = [value for key, value in zip(keys, values) if key[0]==cat]
            time_labels = [key[1] for key in keys if key[0]==cat]
            self.time_group._plot(cat, stat_name, time_labels, filtered_values, fig)

        plt.legend()
        plt.title(stat_name + " " + self.name)
        plt.savefig(PLOT_PATH + "/" + self.name+" "+stat_name+".png")
        plt.close('all') 
Example 38
Project: DataSciUF-Tutorial-Student   Author: jdamiani27   File: class_vis.py    MIT License 5 votes vote down vote up
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 10.5
    y_min = 0.0; y_max = 10.5
    
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==2]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==2]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==4]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==4]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="benign")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="malignant")
    plt.legend()
    plt.xlabel("uniformity_cell_shape")
    plt.ylabel("bare_nuclei")

    plt.savefig("test.png") 
Example 39
Project: cs294-112_hws   Author: xuwd11   File: plot.py    MIT License 5 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('logdir', nargs='*')
    parser.add_argument('--legend', nargs='*')
    parser.add_argument('--value', default='AverageReturn', nargs='*')
    parser.add_argument('--save_name', type=str, default='results')
    args = parser.parse_args()
    
    if not os.path.exists('results'):
        os.makedirs('results')
    
    use_legend = False
    if args.legend is not None:
        assert len(args.legend) == len(args.logdir), \
            "Must give a legend title for each set of experiments."
        use_legend = True

    data = []
    if use_legend:
        for logdir, legend_title in zip(args.logdir, args.legend):
            data += get_datasets(logdir, legend_title)
    else:
        for logdir in args.logdir:
            data += get_datasets(logdir)

    if isinstance(args.value, list):
        values = args.value
    else:
        values = [args.value]
    for value in values:
        plot_data(data, value=value)
    plt.savefig(
        os.path.join('results', args.save_name + '.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 40
Project: cs294-112_hws   Author: xuwd11   File: plot_part1.py    MIT License 5 votes vote down vote up
def plot_11(data):
    r1, r2, r3, r4 = data
    plt.figure()
    add_plot(r1, 'MeanReward100Episodes', 'MeanReward100Episodes');
    add_plot(r1, 'BestMeanReward', 'BestMeanReward');
    plt.xlabel('Time step');
    plt.ylabel('Reward');
    plt.legend();
    plt.savefig(
        os.path.join('results', 'p11.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 41
Project: cs294-112_hws   Author: xuwd11   File: plot.py    MIT License 5 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('logdir', nargs='*')
    parser.add_argument('--legend', nargs='*')
    parser.add_argument('--value', default='AverageReturn', nargs='*')
    parser.add_argument('--save_name', type=str, default='results')
    args = parser.parse_args()
    
    if not os.path.exists('results'):
        os.makedirs('results')
    
    use_legend = False
    if args.legend is not None:
        assert len(args.legend) == len(args.logdir), \
            "Must give a legend title for each set of experiments."
        use_legend = True

    data = []
    if use_legend:
        for logdir, legend_title in zip(args.logdir, args.legend):
            data += get_datasets(logdir, legend_title)
    else:
        for logdir in args.logdir:
            data += get_datasets(logdir)

    if isinstance(args.value, list):
        values = args.value
    else:
        values = [args.value]
    for value in values:
        plot_data(data, value=value)
    plt.savefig(
        os.path.join('results', args.save_name + '.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 42
Project: cs294-112_hws   Author: xuwd11   File: plot.py    MIT License 5 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('logdir', nargs='*')
    parser.add_argument('--legend', nargs='*')
    parser.add_argument('--value', default='AverageReturn', nargs='*')
    parser.add_argument('--save_name', type=str, default='results')
    args = parser.parse_args()
    
    if not os.path.exists('results'):
        os.makedirs('results')
    
    use_legend = False
    if args.legend is not None:
        assert len(args.legend) == len(args.logdir), \
            "Must give a legend title for each set of experiments."
        use_legend = True

    data = []
    if use_legend:
        for logdir, legend_title in zip(args.logdir, args.legend):
            data += get_datasets(logdir, legend_title)
    else:
        for logdir in args.logdir:
            data += get_datasets(logdir)

    if isinstance(args.value, list):
        values = args.value
    else:
        values = [args.value]
    for value in values:
        plot_data(data, value=value)
    plt.savefig(
        os.path.join('results', args.save_name + '.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 43
Project: cs294-112_hws   Author: xuwd11   File: pointmass.py    MIT License 5 votes vote down vote up
def visualize(self, states, itr, dirname):
        if states is None:
            states = np.load(os.path.join(dirname, '{}.npy'.format(itr)))
        indices = np.array([int(self.preprocess(s)) for s in states])
        a = np.zeros(int(self.grid_size))
        for i in indices:
            a[i] += 1
        max_freq = np.max(a)
        a/=float(max_freq)  # normalize
        a = np.reshape(a, (self.scale, self.scale))
        ax = sns.heatmap(a)
        plt.savefig(os.path.join(dirname, '{}.png'.format(itr)))
        plt.close() 
Example 44
Project: cs294-112_hws   Author: xuwd11   File: plot.py    MIT License 5 votes vote down vote up
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('logdir', nargs='*')
    parser.add_argument('--legend', nargs='*')
    parser.add_argument('--value', default='LastEpReturn', nargs='*')
    parser.add_argument('--save_name', type=str, default='results')
    args = parser.parse_args()
    
    if not os.path.exists('results'):
        os.makedirs('results')
    
    use_legend = False
    if args.legend is not None:
        assert len(args.legend) == len(args.logdir), \
            "Must give a legend title for each set of experiments."
        use_legend = True

    data = []
    if use_legend:
        for logdir, legend_title in zip(args.logdir, args.legend):
            data += get_datasets(logdir, legend_title)
    else:
        for logdir in args.logdir:
            data += get_datasets(logdir)

    if isinstance(args.value, list):
        values = args.value
    else:
        values = [args.value]
    for value in values:
        plot_data(data, value=value)
    plt.savefig(
        os.path.join('results', args.save_name + '.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 45
Project: relay-bench   Author: uwsampl   File: plot_util.py    Apache License 2.0 5 votes vote down vote up
def save(self, dirname, filename):
        outfile = prepare_out_file(dirname, filename)
        plt.savefig(outfile, dpi=500, bbox_inches='tight')
        plt.close() 
Example 46
Project: lirpg   Author: Hwhitetooth   File: mujoco_dset.py    MIT License 5 votes vote down vote up
def plot(self):
        import matplotlib.pyplot as plt
        plt.hist(self.rets)
        plt.savefig("histogram_rets.png")
        plt.close() 
Example 47
Project: lirpg   Author: Hwhitetooth   File: gail-eval.py    MIT License 5 votes vote down vote up
def plot(env_name, bc_log, gail_log, stochastic):
    upper_bound = bc_log['upper_bound']
    bc_avg_ret = bc_log['avg_ret']
    gail_avg_ret = gail_log['avg_ret']
    plt.plot(CONFIG['traj_limitation'], upper_bound)
    plt.plot(CONFIG['traj_limitation'], bc_avg_ret)
    plt.plot(CONFIG['traj_limitation'], gail_avg_ret)
    plt.xlabel('Number of expert trajectories')
    plt.ylabel('Accumulated reward')
    plt.title('{} unnormalized scores'.format(env_name))
    plt.legend(['expert', 'bc-imitator', 'gail-imitator'], loc='lower right')
    plt.grid(b=True, which='major', color='gray', linestyle='--')
    if stochastic:
        title_name = 'result/{}-unnormalized-stochastic-scores.png'.format(env_name)
    else:
        title_name = 'result/{}-unnormalized-deterministic-scores.png'.format(env_name)
    plt.savefig(title_name)
    plt.close()

    bc_normalized_ret = bc_log['normalized_ret']
    gail_normalized_ret = gail_log['normalized_ret']
    plt.plot(CONFIG['traj_limitation'], np.ones(len(CONFIG['traj_limitation'])))
    plt.plot(CONFIG['traj_limitation'], bc_normalized_ret)
    plt.plot(CONFIG['traj_limitation'], gail_normalized_ret)
    plt.xlabel('Number of expert trajectories')
    plt.ylabel('Normalized performance')
    plt.title('{} normalized scores'.format(env_name))
    plt.legend(['expert', 'bc-imitator', 'gail-imitator'], loc='lower right')
    plt.grid(b=True, which='major', color='gray', linestyle='--')
    if stochastic:
        title_name = 'result/{}-normalized-stochastic-scores.png'.format(env_name)
    else:
        title_name = 'result/{}-normalized-deterministic-scores.png'.format(env_name)
    plt.ylim(0, 1.6)
    plt.savefig(title_name)
    plt.close() 
Example 48
Project: SNN   Author: arnogranier   File: plots.py    MIT License 5 votes vote down vote up
def savefig(path):
    """matplotlib.savefig"""
    plt.savefig(path) 
Example 49
Project: SLiPy   Author: glentner   File: Plot.py    GNU General Public License v2.0 5 votes vote down vote up
def save(self, filename):
        """
        Save plot to `filename`. Must have extension for formatting.
        """
        if type(filename) is not str:
            raise PlotError('`filename` should be of type str.')
        if len(filename.split('.')) < 2:
            raise PlotError('`filename` needs an extension.')

        plt.savefig(filename, format=filename.split('.')[-1]) 
Example 50
Project: where   Author: kartverket   File: sisre_comparison_report.py    MIT License 5 votes vote down vote up
def _plot_bar_sisre_signal_combination_rms(df, fid, figure_dir, write_table=False):
    """Generate bar plot with monthly SISRE RMS for each GNSS signal combination

    Args:
       df (Dataframe):          Dataframe with time, satellite, system and GNSS signal combinations as columns
       fid (_io.TextIOWrapper): File object.
       figure_dir (PosixPath):  Figure directory.
       write_table (bool):      Write table.
    """
    df_monthly_rms = df.set_index("time.gps").resample("M", how=lambda x: np.sqrt(np.nanmean(np.square(x))))
    df_monthly_rms.index = df_monthly_rms.index.strftime("%b-%Y")
    df_monthly_rms.transpose().plot(kind="bar")

    if write_table:
        _write_dataframe_to_markdown(
            fid,
            df_monthly_rms.transpose(),
            float_format="6.3f",
            caption=f"RMS SISE results for signal combinations in meter: ",
        )

    plt.xlabel("Signal combination for single- and dual-frequency users")
    plt.xticks(rotation=0)
    plt.ylabel("SISE RMS [m]")
    # plt.legend(bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0., ncol=1) #legend on right side
    # plt.legend(bbox_to_anchor=(1, 1.15), loc=1, borderaxespad=0., ncol=3) #legend on top
    plt.legend(bbox_to_anchor=(0.8, -0.15), loc=1, borderaxespad=0.0, ncol=3)  # legend below
    # plt.legend(bbox_to_anchor=(0.8, -0.1), loc=1, borderaxespad=0., ncol=3) #legend below without xlabel
    plt.tight_layout()
    plt.savefig(figure_dir / f"plot_bar_sisre_signal_combination_rms.{FIGURE_FORMAT}")
    plt.clf()  # clear the current figure

    fid.write(
        f"![Monthly RMS of global average SISE for single- and dual-frequency users]({figure_dir}/plot_bar_sisre_signal_combination_rms.{FIGURE_FORMAT})\n"
    )
    fid.write("\\newpage\n")