How to use the matplotlib.pyplot.savefig function in matplotlib

To help you get started, we’ve selected a few matplotlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serrano-s / attn-tests / figure_making / figure_maker_single_dataset.py View on Github external
assert len(tup[1]) == len(tup[2])
        for i in range(len(tup[1])):
            if True or "flip" in y_label or tup[2][i] < 2.5:
                list_of_row_dicts.append({title_of_each_graph: tup[0], x_label: tup[1][i], y_label: tup[2][i],
                                          "AllTheSameInCol": "filler"})
            else:
                print("Excluding a data point for " + y_label)
    data_to_plot = pd.DataFrame(list_of_row_dicts)
    marker_format_dict = {'alpha': 0.15, 's': 2}
    if 'flip' in y_label:
        marker_format_dict["s"] = 10
    g = sns.lmplot(x=x_label, y=y_label, col=title_of_each_graph, hue="AllTheSameInCol", palette=None,
                   data = data_to_plot, col_wrap = 2, legend=False,
                   scatter_kws=marker_format_dict, sharey=False, sharex=False)
    print("Saving file to " + filename)
    plt.savefig(filename, bbox_inches='tight')
github arthurmensch / modl / exps / exp_decompose_fmri.py View on Github external
step_size=step_size,
                             alpha=alpha,
                             callback=cb,
                             )
    dict_fact.fit(train_imgs)
    dict_fact.components_img_.to_filename(join(artifact_dir, 'components.nii.gz'))
    fig = plt.figure()
    display_maps(fig, dict_fact.components_img_)
    plt.savefig(join(artifact_dir, 'components.png'))

    fig, ax = plt.subplots(1, 1)
    ax.plot(cb.cpu_time, cb.score, marker='o')
    _run.info['time'] = cb.cpu_time
    _run.info['score'] = cb.score
    _run.info['iter'] = cb.iter
    plt.savefig(join(artifact_dir, 'score.png'))
github ROBelgium / MSNoise / msnoise / plots / timing.py View on Github external
plt.grid(True)
            del alldf
    if outfile:
        if outfile.startswith("?"):
            if len(mov_stacks) == 1:
                outfile = outfile.replace('?', '%s-f%i-m%i-M%s' % (components,
                                                                   filterid,
                                                                   mov_stack,
                                                                   dttname))
            else:
                outfile = outfile.replace('?', '%s-f%i-M%s' % (components,
                                                               filterid,
                                                               dttname))
        outfile = "timing " + outfile
        print("output to:", outfile)
        plt.savefig(outfile)
    if show:
        plt.show()
github BreezeWhite / Music-Transcription-with-Semantic-Segmentation / project / utils.py View on Github external
def to_midi(pred, out_path, velocity=100, threshold=0.4, t_unit=0.02):
    midi = pretty_midi.PrettyMIDI()
    piano = pretty_midi.Instrument(program=0) 
    
    notes = []
    pred = np.where(pred>threshold, 1, 0)   
    pred = merge_channels(pred)
    pitch_offset = librosa.note_to_midi("A0")
    #print("Transformed shape: ", pred.shape)
    
    plt.imshow(pred.transpose(), origin="lower", aspect=20)
    plt.savefig("{}.png".format(out_path), dpi=250)
    
    for i in range(pred.shape[1]):
        pp = pred[:, i]
        candy = np.where(pp > 0.5)[0]
        if len(candy) == 0:
            # No pitch present
            continue
        
        shift = np.insert(candy, 0, 0)[:-1]
        diff = candy - shift
        on_idx = np.where(diff>1)[0]
        onsets = candy[on_idx]
        offsets = shift[on_idx[1:]]
        offsets = np.append(offsets, candy[-1])

        for ii in range(len(onsets)):
github PIQuIL / QuCumber / symmetries.py View on Github external
axes[0].set_xlabel("$i$")

    label1 = "$\sum_{i}{W_{ij}}$"
    label2 = "$c_{j}$"
    label3 = "{0}/{1}".format(label1,label2)
    xpoints = list(range(len(rowSums)))
    # ax = plt.figure().gca()
    # ax.xaxis.set_major_locator(MaxNLocator(integer = True))
    axes[1].plot(xpoints,rowSums,label = label1)
    axes[1].plot(xpoints,hiddenBias,label = label2)
    axes[1].plot(xpoints,rowSums/hiddenBias,"r--",label = label3,linewidth = 2)
    axes[1].axhline(0,color = "k")
    axes[1].set_ylim(-14,14)
    axes[1].legend()
    axes[1].set_xlabel("$j$")
    plt.savefig("Symmetries")
    plt.clf()
    plt.close()

    vbiases = []
    hbiases = []
    for i in range(len(weights)):
        vindex = np.argmax(abs(weights[i]))
        vbias = visibleBias[vindex]
        hbias = hiddenBias[i]
        vbiases.append(vbias)
        hbiases.append(hbias)
    vbiases = np.array(vbiases)
    hbiases = np.array(hbiases)

    label1 = "$b_{j}^{Strong}$"
    label2 = "$c_{i}$"
github Lab41 / sunny-side-up / src / glove / glove / glove.py View on Github external
dst = (np.dot(self.word_vectors, word_vec)
               / np.linalg.norm(self.word_vectors, axis=1)
               / np.linalg.norm(word_vec))
        word_ids = np.argsort(-dst)

        # build histogram
        n, bins, patches = plt.hist(dst, range=(-1, 1), weights=np.ones_like(dst)/float(len(dst)), facecolor='green', alpha=0.5)
        plt.xlabel('Similarity')
        plt.ylabel('Probability')
        plt.title('Histogram of word similarities for `'+self.inverse_dictionary[word_ids[0]]+'`')

        # show or save
        if show_hist:
            plt.show()
        else:
            plt.savefig('./similarity_vs_probability.png')

        if similar:
            return [(self.inverse_dictionary[x], dst[x]) for x in word_ids[:number]
                if x in self.inverse_dictionary]
        else:
            return [(self.inverse_dictionary[x], dst[x]) for x in word_ids[-number:]
                if x in self.inverse_dictionary]
github BinRoot / TensorFlow-Book / ch10_rnn / regression.py View on Github external
def plot_results(train_x, predictions, actual, filename):
    plt.figure()
    num_train = len(train_x)
    plt.plot(list(range(num_train)), train_x, color='b', label='training data')
    plt.plot(list(range(num_train, num_train + len(predictions))), predictions, color='r', label='predicted')
    plt.plot(list(range(num_train, num_train + len(actual))), actual, color='g', label='test data')
    plt.legend()
    if filename is not None:
        plt.savefig(filename)
    else:
        plt.show()
github f-dangel / backpack / exp / plotting / plotting.py View on Github external
def save_as_tikz(out_file, pdf_preview=True):
        """Save TikZ figure using matplotlib2tikz. Optional PDF out."""
        tex_file, pdf_file = ['{}.{}'.format(out_file, extension)
                              for extension in ['tex', 'pdf']]
        tikz_save(tex_file, 
                  override_externals = True,
                  # define these two macros in your .tex document
                  figureheight = r'\figheight',
                  figurewidth = r'\figwidth',
                  tex_relative_path_to_data = '../../fig/',
                  extra_axis_parameters = {'mystyle'})
        if pdf_preview:
            plt.savefig(pdf_file, bbox_inches='tight')
github ZainNasrullah / music-artist-classification-crnn / src / utility.py View on Github external
create_dataset(artist_folder='artists', save_folder='song_data',
                       sr=16000, n_mels=128, n_fft=2048,
                       hop_length=512)

    if create_visuals:
        # Create spectrogram for a specific song
        visualize_spectrogram(
            'artists/u2/The_Joshua_Tree/' +
            '02-I_Still_Haven_t_Found_What_I_m_Looking_For.mp3',
            offset=60, duration=29.12)

        # Create spectrogram subplots
        create_spectrogram_plots(artist_folder='artists', sr=16000, n_mels=128,
                                 n_fft=2048, hop_length=512)
        if save_visuals:
            plt.savefig(os.path.join('spectrograms.png'),
                        bbox_inches="tight")
github persistforever / cifar10-tensorflow / exps / cifar10-v11 / log_analyzer.py View on Github external
plt.xlabel('# of epoch')
	plt.ylabel('accuracy')
	"""
	plt.subplot(122)
	p1 = plt.plot(valid_precision_idxs1, valid_precision_list1, '.--', color='#6495ED')
	p2 = plt.plot(valid_precision_idxs2, valid_precision_list2, '.--', color='#FF6347')
	p3 = plt.plot(valid_precision_idxs3, valid_precision_list3, '.--', color='#4EEE94')
	plt.legend((p1[0], p2[0], p3[0]), ('lr = 0.01', 'lr = 0.01~0.001', 'lr = 0.01~0.001~0.0005'))
	plt.grid(True)
	plt.title('cifar10 image classification valid precision')
	plt.xlabel('# of epoch')
	plt.ylabel('accuracy')
	plt.axis([0, 500, 0.7, 0.9])

	# plt.show()
	plt.savefig('E:\\Github\cifar10-tensorflow\\exps\cifar10-v11\cifar10-v11.png', dpi=72, format='png')