Python matplotlib.pyplot.suptitle() Examples

The following are 30 code examples of matplotlib.pyplot.suptitle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: shrinkage.py    From onsager_deep_learning with MIT License 6 votes vote down vote up
def show_shrinkage(shrink_func,theta,**kwargs):
    tf.reset_default_graph()
    tf.set_random_seed(kwargs.get('seed',1) )

    N = kwargs.get('N',500)
    L = kwargs.get('L',4)
    nsigmas = kwargs.get('sigmas',10)
    shape = (N,L)
    rvar = 1e-4
    r = np.reshape( np.linspace(0,nsigmas,N*L)*math.sqrt(rvar),shape)
    r_ = tfcf(r)
    rvar_ = tfcf(np.ones(L)*rvar)

    xhat_,dxdr_ = shrink_func(r_,rvar_ ,tfcf(theta))

    with tf.Session() as sess:
        sess.run( tf.global_variables_initializer() )
        xhat = sess.run(xhat_)
    import matplotlib.pyplot as plt
    plt.figure(1)
    plt.plot(r.reshape(-1),r.reshape(-1),'y')
    plt.plot(r.reshape(-1),xhat.reshape(-1),'b')
    if kwargs.has_key('title'):
        plt.suptitle(kwargs['title'])
    plt.show() 
Example #2
Source File: rattlesnake.py    From rattlesnake with MIT License 6 votes vote down vote up
def plot_results(data, nth_iteration):
    """
    Plots the list it receives and cuts off the first ten entries to circumvent the plotting of initial silence

    :param data: A list of data to be plotted
    :param nth_iteration: Used for the label of the x axis
    """

    # Plot the data
    plt.plot(data[10:])

    # Label the axes
    plt.xlabel('Time (every {}th {} byte)'.format(nth_iteration, CHUNK))
    plt.ylabel('Volume level difference (in dB)')

    # Calculate and output the absolute median difference level
    plt.suptitle('Difference - Median (in dB): {}'.format(np.round(np.fabs(np.median(data)), decimals=5)), fontsize=14)

    # Display the plotted graph
    plt.show() 
Example #3
Source File: tcp-plot.py    From bene with GNU General Public License v2.0 6 votes vote down vote up
def queue(self,filename):
        plt.figure()
        df = pd.read_csv('queue.csv')
        size = df[df.Event == 'size'].copy()
        ax1 = size.plot(x='Time',y='Queue Size')
        # drop
        try:
            drop = df[df.Event == 'drop'].copy()
            drop['Queue Size']  =  df['Queue Size'] + 1
            ax = drop.plot(x='Time',y='Queue Size',kind='scatter',marker='x',s=10,ax=ax1)
        except:
            pass
        # set the axes
        ax.set_xlabel('Time')
        ax.set_ylabel('Queue Size (packets)')
        plt.suptitle("")
        plt.title("")
        plt.savefig(filename) 
Example #4
Source File: tcp-plot.py    From bene with GNU General Public License v2.0 6 votes vote down vote up
def sequence(self,filename):
        plt.figure()
        df = pd.read_csv('sequence.csv',dtype={'Time':float,'Sequence Number':int})
        df['Sequence Number']  =  df['Sequence Number'] / 1000 % 50
        # send
        send = df[df.Event == 'send'].copy()
        ax1 = send.plot(x='Time',y='Sequence Number',kind='scatter',marker='s',s=2,figsize=(11,3))
        # transmit
        transmit = df[df.Event == 'transmit'].copy()
        transmit.plot(x='Time',y='Sequence Number',kind='scatter',marker='s',s=2,figsize=(11,3),ax=ax1)
        # drop
        try:
            drop = df[df.Event == 'drop'].copy()
            drop.plot(x='Time',y='Sequence Number',kind='scatter',marker='x',s=10,figsize=(11,3),ax=ax1)
        except:
            pass
        # ack
        ack = df[df.Event == 'ack'].copy()
        ax = ack.plot(x='Time',y='Sequence Number',kind='scatter',marker='.',s=2,figsize=(11,3),ax=ax1)
        ax.set_xlim(left=-0.01)
        ax.set_xlabel('Time')
        ax.set_ylabel('Sequence Number')
        plt.suptitle("")
        plt.title("")
        plt.savefig(filename,dpi=300) 
Example #5
Source File: tools.py    From opticspy with MIT License 6 votes vote down vote up
def phase_shift_figure(I,PR,type):
	"""
	Draw PSI Interferograms, several types.
	"""
	if type == "4-step":
		f, axarr = __plt__.subplots(2, 2, figsize=(9, 9), dpi=80)
		axarr[0, 0].imshow(-I[0], extent=[-PR,PR,-PR,PR],cmap=__cm__.Greys)
		axarr[0, 0].set_title(r'$Phase\ shift: 0$',fontsize=16)
		axarr[0, 1].imshow(-I[1], extent=[-PR,PR,-PR,PR],cmap=__cm__.Greys)
		axarr[0, 1].set_title(r'$Phase\ shift: 1/2\pi$',fontsize=16)
		axarr[1, 0].imshow(-I[2], extent=[-PR,PR,-PR,PR],cmap=__cm__.Greys)
		axarr[1, 0].set_title(r'$Phase\ shift: \pi$',fontsize=16)
		axarr[1, 1].imshow(-I[3], extent=[-PR,PR,-PR,PR],cmap=__cm__.Greys)
		axarr[1, 1].set_title(r'$Phase\ shift: 3/2\pi$',fontsize=16)
		__plt__.suptitle('4-step Phase Shift Interferograms',fontsize=16)
		__plt__.show()
	else:
		print("No this type of figure") 
Example #6
Source File: test.py    From cloudless with Apache License 2.0 6 votes vote down vote up
def _plot_loss(training_details, validation_details, note, output_graph_path, solver):
    """
    Plots training/validation loss side by side.
    """
    print "\tPlotting training/validation loss..."
    fig, ax1 = plt.subplots()
    ax1.plot(training_details["iters"], training_details["loss"], "b-")
    ax1.set_xlabel("Iterations")
    ax1.set_ylabel("Training Loss", color="b")
    for tl in ax1.get_yticklabels():
        tl.set_color("b")

    ax2 = ax1.twinx()
    ax2.plot(validation_details["iters"], validation_details["loss"], "r-")
    ax2.set_ylabel("Validation Loss", color="r")
    for tl in ax2.get_yticklabels():
        tl.set_color("r")

    plt.suptitle("Iterations vs. Training/Validation Loss", fontsize=14)
    plt.title(_get_hyperparameter_details(note, solver), style="italic", fontsize=12)

    filename = output_graph_path + ".loss.png"
    plt.savefig(filename)
    plt.close()
    print("\t\tGraph saved to %s" % filename) 
Example #7
Source File: test_mosaicplot.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_axes_labeling():
    from numpy.random import rand
    key_set = (['male', 'female'], ['old', 'adult', 'young'],
               ['worker', 'unemployed'], ['yes', 'no'])
    # the cartesian product of all the categories is
    # the complete set of categories
    keys = list(product(*key_set))
    data = OrderedDict(zip(keys, rand(len(keys))))
    lab = lambda k: ''.join(s[0] for s in k)
    fig, (ax1, ax2) = pylab.subplots(1, 2, figsize=(16, 8))
    mosaic(data, ax=ax1, labelizer=lab, horizontal=True, label_rotation=45)
    mosaic(data, ax=ax2, labelizer=lab, horizontal=False,
        label_rotation=[0, 45, 90, 0])
    #fig.tight_layout()
    fig.suptitle("correct alignment of the axes labels")
    #pylab.show()
    pylab.close('all') 
Example #8
Source File: visualise_attention.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()
    plt.suptitle(title) 
Example #9
Source File: original_images_example.py    From Neural-Network-Programming-with-TensorFlow with MIT License 6 votes vote down vote up
def main(self):
        X_train, X_test = self.standard_scale(mnist.train.images, mnist.test.images)

        original_imgs = X_test[:100]
        plt.figure(1, figsize=(10, 10))

        for i in range(0, 100):
            im = original_imgs[i].reshape((28, 28))
            ax = plt.subplot(10, 10, i + 1)
            for label in (ax.get_xticklabels() + ax.get_yticklabels()):
                label.set_fontsize(8)

            plt.imshow(im, cmap="gray", clim=(0.0, 1.0))
        plt.suptitle(' Original Images', fontsize=15, y=0.95)
        plt.savefig('figures/original_images.png')
        plt.show() 
Example #10
Source File: plant_analysis.py    From OpenOA with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_aep_boxplot(self, param, lab):
        """                                                                                                                                                                                        
        Plot box plots of AEP results sliced by a specified Monte Carlo parameter                                                                                                                  

        Args:                                                                                                                                                                                      
           param( :obj:`list'): The Monte Carlo parameter on which to split the AEP results
           lab(:obj:'str'): The name to use for the parameter when producing the figure
        
        Returns:                                                                                                                                                                                   
            (none)                                                                                                                                                                               
        """

        import matplotlib.pyplot as plt
        sim_results = self.results

        tmp_df=pd.DataFrame(data={'aep': sim_results.aep_GWh, 'param': param})
        tmp_df.boxplot(column='aep',by='param',figsize=(8,6))
        plt.ylabel('AEP (GWh/yr)')
        plt.xlabel(lab)
        plt.title('AEP estimates by %s' % lab)
        plt.suptitle("")
        plt.tight_layout()
        return plt 
Example #11
Source File: test_mosaicplot.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_mosaic_simple():
    # display a simple plot of 4 categories of data, splitted in four
    # levels with increasing size for each group
    # creation of the levels
    key_set = (['male', 'female'], ['old', 'adult', 'young'],
               ['worker', 'unemployed'], ['healty', 'ill'])
    # the cartesian product of all the categories is
    # the complete set of categories
    keys = list(product(*key_set))
    data = OrderedDict(zip(keys, range(1, 1 + len(keys))))
    # which colours should I use for the various categories?
    # put it into a dict
    props = {}
    #males and females in blue and red
    props[('male',)] = {'color': 'b'}
    props[('female',)] = {'color': 'r'}
    # all the groups corresponding to ill groups have a different color
    for key in keys:
        if 'ill' in key:
            if 'male' in key:
                props[key] = {'color': 'BlueViolet' , 'hatch': '+'}
            else:
                props[key] = {'color': 'Crimson' , 'hatch': '+'}
    # mosaic of the data, with given gaps and colors
    mosaic(data, gap=0.05, properties=props, axes_label=False)
    pylab.suptitle('syntetic data, 4 categories (plot 2 of 4)')
    #pylab.show()
    pylab.close('all') 
Example #12
Source File: test_mosaicplot.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_mosaic():
    # make the same analysis on a known dataset

    # load the data and clean it a bit
    affairs = datasets.fair.load_pandas()
    datas = affairs.exog
    # any time greater than 0 is cheating
    datas['cheated'] = affairs.endog > 0
    # sort by the marriage quality and give meaningful name
    # [rate_marriage, age, yrs_married, children,
    # religious, educ, occupation, occupation_husb]
    datas = sort_values(datas, ['rate_marriage', 'religious'])

    num_to_desc = {1: 'awful', 2: 'bad', 3: 'intermediate',
                      4: 'good', 5: 'wonderful'}
    datas['rate_marriage'] = datas['rate_marriage'].map(num_to_desc)
    num_to_faith = {1: 'non religious', 2: 'poorly religious', 3: 'religious',
                      4: 'very religious'}
    datas['religious'] = datas['religious'].map(num_to_faith)
    num_to_cheat = {False: 'faithful', True: 'cheated'}
    datas['cheated'] = datas['cheated'].map(num_to_cheat)
    # finished cleaning
    fig, ax = pylab.subplots(2, 2)
    mosaic(datas, ['rate_marriage', 'cheated'], ax=ax[0, 0],
                title='by marriage happiness')
    mosaic(datas, ['religious', 'cheated'], ax=ax[0, 1],
                title='by religiosity')
    mosaic(datas, ['rate_marriage', 'religious', 'cheated'], ax=ax[1, 0],
                title='by both', labelizer=lambda k:'')
    ax[1, 0].set_xlabel('marriage rating')
    ax[1, 0].set_ylabel('religion status')
    mosaic(datas, ['religious', 'rate_marriage'], ax=ax[1, 1],
                title='inter-dependence', axes_label=False)
    pylab.suptitle("extramarital affairs (plot 3 of 4)")
    #pylab.show()
    pylab.close('all') 
Example #13
Source File: test_mosaicplot.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_mosaic_very_complex():
    # make a scattermatrix of mosaic plots to show the correlations between
    # each pair of variable in a dataset. Could be easily converted into a
    # new function that does this automatically based on the type of data
    key_name = ['gender', 'age', 'health', 'work']
    key_base = (['male', 'female'], ['old', 'young'],
                    ['healty', 'ill'], ['work', 'unemployed'])
    keys = list(product(*key_base))
    data = OrderedDict(zip(keys, range(1, 1 + len(keys))))
    props = {}
    props[('male', 'old')] = {'color': 'r'}
    props[('female',)] = {'color': 'pink'}
    L = len(key_base)
    fig, axes = pylab.subplots(L, L)
    for i in range(L):
        for j in range(L):
            m = set(range(L)).difference(set((i, j)))
            if i == j:
                axes[i, i].text(0.5, 0.5, key_name[i],
                                ha='center', va='center')
                axes[i, i].set_xticks([])
                axes[i, i].set_xticklabels([])
                axes[i, i].set_yticks([])
                axes[i, i].set_yticklabels([])
            else:
                ji = max(i, j)
                ij = min(i, j)
                temp_data = OrderedDict([((k[ij], k[ji]) + tuple(k[r] for r in m), v)
                                            for k, v in iteritems(data)])

                keys = list(iterkeys(temp_data))
                for k in keys:
                    value = _reduce_dict(temp_data, k[:2])
                    temp_data[k[:2]] = value
                    del temp_data[k]
                mosaic(temp_data, ax=axes[i, j], axes_label=False,
                       properties=props, gap=0.05, horizontal=i > j)
    pylab.suptitle('old males should look bright red,  (plot 4 of 4)')
    #pylab.show()
    pylab.close('all') 
Example #14
Source File: test_mosaicplot.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_data_conversion():
    # It will not reorder the elements
    # so the dictionary will look odd
    # as it key order has the c and b
    # keys swapped
    import pandas
    fig, ax = pylab.subplots(4, 4)
    data = {'ax': 1, 'bx': 2, 'cx': 3}
    mosaic(data, ax=ax[0, 0], title='basic dict', axes_label=False)
    data = pandas.Series(data)
    mosaic(data, ax=ax[0, 1], title='basic series', axes_label=False)
    data = [1, 2, 3]
    mosaic(data, ax=ax[0, 2], title='basic list', axes_label=False)
    data = np.asarray(data)
    mosaic(data, ax=ax[0, 3], title='basic array', axes_label=False)

    data = {('ax', 'cx'): 1, ('bx', 'cx'): 2, ('ax', 'dx'): 3, ('bx', 'dx'): 4}
    mosaic(data, ax=ax[1, 0], title='compound dict', axes_label=False)
    mosaic(data, ax=ax[2, 0], title='inverted keys dict', index=[1, 0], axes_label=False)
    data = pandas.Series(data)
    mosaic(data, ax=ax[1, 1], title='compound series', axes_label=False)
    mosaic(data, ax=ax[2, 1], title='inverted keys series', index=[1, 0])
    data = [[1, 2], [3, 4]]
    mosaic(data, ax=ax[1, 2], title='compound list', axes_label=False)
    mosaic(data, ax=ax[2, 2], title='inverted keys list', index=[1, 0])
    data = np.array([[1, 2], [3, 4]])
    mosaic(data, ax=ax[1, 3], title='compound array', axes_label=False)
    mosaic(data, ax=ax[2, 3], title='inverted keys array', index=[1, 0], axes_label=False)

    gender = ['male', 'male', 'male', 'female', 'female', 'female']
    pet = ['cat', 'dog', 'dog', 'cat', 'dog', 'cat']
    data = pandas.DataFrame({'gender': gender, 'pet': pet})
    mosaic(data, ['gender'], ax=ax[3, 0], title='dataframe by key 1', axes_label=False)
    mosaic(data, ['pet'], ax=ax[3, 1], title='dataframe by key 2', axes_label=False)
    mosaic(data, ['gender', 'pet'], ax=ax[3, 2], title='both keys', axes_label=False)
    mosaic(data, ['pet', 'gender'], ax=ax[3, 3], title='keys inverted', axes_label=False)

    pylab.suptitle('testing data conversion (plot 1 of 4)')
    #pylab.show()
    pylab.close('all') 
Example #15
Source File: srm_image_prediction_example_distributed.py    From brainiak with Apache License 2.0 5 votes vote down vote up
def plot_confusion_matrix(cm, title="Confusion Matrix"):
    """Plots a confusion matrix for each subject
    """
    import matplotlib.pyplot as plt
    import math
    plt.figure()
    subjects = len(cm)
    root_subjects = math.sqrt(subjects)
    cols = math.ceil(root_subjects)
    rows = math.ceil(subjects/cols)
    classes = cm[0].shape[0]
    for subject in range(subjects):
        plt.subplot(rows, cols, subject+1)
        plt.imshow(cm[subject], interpolation='nearest', cmap=plt.cm.bone)
        plt.xticks(np.arange(classes), range(1, classes+1))
        plt.yticks(np.arange(classes), range(1, classes+1))
        cbar = plt.colorbar(ticks=[0.0, 1.0], shrink=0.6)
        cbar.set_clim(0.0, 1.0)
        plt.xlabel("Predicted")
        plt.ylabel("True label")
        plt.title("{0:d}".format(subject + 1))
    plt.suptitle(title)
    plt.tight_layout()
    plt.show()

# Load the input data that contains the image stimuli and its labels for training a classifier 
Example #16
Source File: srm_image_prediction_example.py    From brainiak with Apache License 2.0 5 votes vote down vote up
def plot_confusion_matrix(cm, title="Confusion Matrix"):
    """Plots a confusion matrix for each subject
    """
    import matplotlib.pyplot as plt
    import math
    plt.figure()
    subjects = len(cm)
    root_subjects = math.sqrt(subjects)
    cols = math.ceil(root_subjects)
    rows = math.ceil(subjects/cols)
    classes = cm[0].shape[0]
    for subject in range(subjects):
        plt.subplot(rows, cols, subject+1)
        plt.imshow(cm[subject], interpolation='nearest', cmap=plt.cm.bone)
        plt.xticks(np.arange(classes), range(1, classes+1))
        plt.yticks(np.arange(classes), range(1, classes+1))
        cbar = plt.colorbar(ticks=[0.0, 1.0], shrink=0.6)
        cbar.set_clim(0.0, 1.0)
        plt.xlabel("Predicted")
        plt.ylabel("True label")
        plt.title("{0:d}".format(subject + 1))
    plt.suptitle(title)
    plt.tight_layout()
    plt.show()

# Load the input data that contains the image stimuli and its labels for training a classifier 
Example #17
Source File: test.py    From cloudless with Apache License 2.0 5 votes vote down vote up
def _plot_accuracy(training_details, validation_details, note, output_graph_path, solver):
    """
    Plots training/validation accuracy over iterations.
    """
    print "\tPlotting training/validation accuracy..."

    fmt = '%.1f%%'
    yticks = mtick.FormatStrFormatter(fmt)

    fig, ax1 = plt.subplots()
    training_percentage = [percent * 100 for percent in training_details["accuracy"]]
    ax1.plot(training_details["iters"], training_percentage, "b-")
    ax1.set_xlabel("Iterations")
    ax1.set_ylabel("Training Accuracy", color="b")
    ax1.yaxis.set_major_formatter(yticks)
    for tl in ax1.get_yticklabels():
        tl.set_color("b")

    ax2 = ax1.twinx()
    validation_percentage = [percent * 100 for percent in validation_details["accuracy"]]
    ax2.plot(validation_details["iters"], validation_percentage, "r-")
    ax2.set_ylabel("Validation Accuracy", color="r")
    ax2.yaxis.set_major_formatter(yticks)
    for tl in ax2.get_yticklabels():
        tl.set_color("r")

    plt.suptitle("Iterations vs. Training/Validation Accuracy", fontsize=14)
    plt.title(_get_hyperparameter_details(note, solver), style="italic", fontsize=12)

    filename = output_graph_path + ".accuracy.png"
    plt.savefig(filename)
    plt.close()
    print("\t\tGraph saved to %s" % filename) 
Example #18
Source File: atlas3.py    From ssbio with MIT License 5 votes vote down vote up
def make_pairplot(self, num_components_to_plot=4, outpath=None, dpi=150):
        # Get columns
        components_to_plot = [self.principal_observations_df.columns[x] for x in range(num_components_to_plot)]

        # Plot
        plot = sns.pairplot(data=self.principal_observations_df, hue=self.observation_colname,
                                vars=components_to_plot, markers=self.markers, size=4)
        plt.subplots_adjust(top=.95)
        plt.suptitle(self.plot_title)

        if outpath:
            plot.fig.savefig(outpath, dpi=dpi)
        else:
            plt.show()
        plt.close() 
Example #19
Source File: tfvis.py    From python-control with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def redraw(self):
        """ Redraw all diagrams """
        self.draw_pz(self.sys)
        
        self.f_bode.clf()
        plt.figure(self.f_bode.number)
        control.matlab.bode(self.sys, logspace(-2, 2))
        plt.suptitle('Bode Diagram')

        self.f_nyquist.clf()
        plt.figure(self.f_nyquist.number)
        control.matlab.nyquist(self.sys, logspace(-2, 2))
        plt.suptitle('Nyquist Diagram')

        self.f_step.clf()
        plt.figure(self.f_step.number)
        try:
            # Step seems to get intro trouble
            # with purely imaginary poles
            tvec, yvec = control.matlab.step(self.sys)
            plt.plot(tvec.T, yvec)
        except:
            print("Error plotting step response")
        plt.suptitle('Step Response')

        self.canvas_pzmap.draw()
        self.canvas_bode.draw()
        self.canvas_step.draw()
        self.canvas_nyquist.draw() 
Example #20
Source File: tcp-plot.py    From bene with GNU General Public License v2.0 5 votes vote down vote up
def cwnd(self,filename):
        plt.figure()
        df = pd.read_csv('cwnd.csv')
        ax = df.plot(x="Time",y="Congestion Window")
        # set the axes
        ax.set_xlabel('Time')
        ax.set_ylabel('Congestion Window (bytes)')
        plt.suptitle("")
        plt.title("")
        plt.savefig(filename) 
Example #21
Source File: test_bbox_tight.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bbox_inches_tight_suptile_legend():
    plt.plot(np.arange(10), label='a straight line')
    plt.legend(bbox_to_anchor=(0.9, 1), loc='upper left')
    plt.title('Axis title')
    plt.suptitle('Figure title')

    # put an extra long y tick on to see that the bbox is accounted for
    def y_formatter(y, pos):
        if int(y) == 4:
            return 'The number 4'
        else:
            return str(y)
    plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))

    plt.xlabel('X axis') 
Example #22
Source File: core.py    From sdwan-harvester with GNU General Public License v2.0 5 votes vote down vote up
def create_pie_chart(elements, suptitle, png, figure_id):
    """
    Create pie chart

    :param elements: dict with elements (dict)
    :param suptitle: name of chart (str)
    :param png: name of output file (str)
    :param figure_id: id of current plot (started with 1) (int)
    :return: None
    """
    values = [value for value in elements.values()]
    keys = [key for key in elements.keys()]
    plt.figure(figure_id)
    plt.subplots_adjust(bottom=.05, left=.01, right=.99, top=.90, hspace=.35)

    explode = [0 for x in range(len(keys))]
    max_value = max(values)
    explode[list(values).index(max_value)] = 0.1

    plt.pie(values, labels=keys,
            autopct=make_autopct(values), explode=explode,
            textprops={'fontsize': PIE_LABEL_FONT_SIZE})
    plt.axis("equal")
    plt.suptitle(suptitle, fontsize=PIE_SUPTITLE_FONT_SIZE)

    plt.gcf().set_dpi(PIE_DPI)
    plt.savefig("{dest}/{png}/{result_file}".format(dest=RESULTS_DIR,
                                                    png=PNG_DIR,
                                                    result_file=png)) 
Example #23
Source File: glm_reporter.py    From nistats with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _add_params_to_plot(table_details, stat_map_plot):
    """
    Inserts thresholding parameters into the stat map plot as figure suptitle.

    Parameters
    ----------
    table_details: Dict[String, Any]
        Dict of parameters and values used in thresholding.

    stat_map_plot: matplotlib.Axes
        Axes object of the stat map plot.

    Returns
    -------
    stat_map_plot: matplotlib.Axes
        Axes object of the stat map plot, with the added suptitle .
    """
    thresholding_params = [':'.join([name, str(val)]) for name, val in
                           table_details[0].items()]
    thresholding_params = '  '.join(thresholding_params)
    suptitle_text = plt.suptitle(thresholding_params,
                                 fontsize=11,
                                 x=.45,
                                 wrap=True,
                                 )
    fig = list(stat_map_plot.axes.values())[0].ax.figure
    fig = _resize_plot_inches(plot=fig,
                              width_change=.2,
                              height_change=1,
                              )
    if stat_map_plot._black_bg:
        suptitle_text.set_color('w')
    return stat_map_plot 
Example #24
Source File: tests.py    From sea_ice_drift with GNU General Public License v3.0 5 votes vote down vote up
def test_rotate_and_match(self):
        ''' shall rotate and match'''
        n1 = get_n(self.testFiles[0])
        n2 = get_n(self.testFiles[1])
        dx, dy, best_a, best_r, best_h, best_result, best_template = rotate_and_match(
                         n1[1], 300, 100, 50, n2[1], 0, [-3,-2,-1,0,1,2,3])
        plt.subplot(1,3,1)
        plt.imshow(n2[1], interpolation='nearest')
        plt.subplot(1,3,2)
        plt.imshow(best_result, interpolation='nearest', vmin=0)
        plt.subplot(1,3,3)
        plt.imshow(best_template, interpolation='nearest')
        plt.suptitle('%f %f %f %f %f' % (dx, dy, best_a, best_r, best_h))
        plt.savefig('sea_ice_drift_tests_%s.png' % inspect.currentframe().f_code.co_name,)
        plt.close('all') 
Example #25
Source File: visualizer.py    From kits19.MIScnn with GNU General Public License v3.0 5 votes vote down vote up
def visualize_evaluation(case_id, vol, truth, pred, eva_path):
    # Color volumes according to truth and pred segmentation
    vol_truth = overlay_segmentation(vol, truth)
    vol_pred = overlay_segmentation(vol, pred)
    # Create a figure and two axes objects from matplot
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Initialize the two subplots (axes) with an empty 512x512 image
    data = np.zeros(vol.shape[1:3])
    ax1.set_title("Ground Truth")
    ax2.set_title("Prediction")
    img1 = ax1.imshow(data)
    img2 = ax2.imshow(data)
    # Update function for both images to show the slice for the current frame
    def update(i):
        plt.suptitle("Case ID: " + str(case_id) + " - " + "Slice: " + str(i))
        img1.set_data(vol_truth[i])
        img2.set_data(vol_pred[i])
        return [img1, img2]
    # Compute the animation (gif)
    ani = animation.FuncAnimation(fig, update, frames=len(truth), interval=10,
                                  repeat_delay=0, blit=False)
    # Set up the output path for the gif
    if not os.path.exists(eva_path):
        os.mkdir(eva_path)
    file_name = "visualization.case_" + str(case_id).zfill(5) + ".gif"
    out_path = os.path.join(eva_path, file_name)
    # Save the animation (gif)
    ani.save(out_path, writer='imagemagick', fps=30)
    # Close the matplot
    plt.close()


#-----------------------------------------------------#
#                     Subroutines                     #
#-----------------------------------------------------#
# Based on: https://github.com/neheller/kits19/blob/master/starter_code/visualize.py 
Example #26
Source File: beacon_analysis.py    From Thrifty with GNU General Public License v3.0 5 votes vote down vote up
def plot(soa0, residuals, discontinuities, avg_snr=None):
    s2m = 3e8 / 2.4e6  # FIXME

    avg_snr_db = 10 * np.log10(avg_snr)

    print("residuals: std dev = {:.01f} m; max = {:.01f} m; "
          "avg corr snr = {:.01f}"
          .format(np.std(residuals) * s2m,
                  np.max(np.abs(residuals)) * s2m,
                  avg_snr_db))

    plt.figure(figsize=(11, 6))
    plt.subplot(1, 2, 1)
    plt.plot(soa0, residuals * S2M, '.-')
    plt.title("Residuals")
    plt.xlabel("RX sample")
    plt.ylabel("Residual (samples)")
    plt.grid()
    # plt.ylim([-0.5, 0.5])

    for discontinuity in discontinuities:
        plt.axvline(discontinuity, color='k')

    plt.subplot(1, 2, 2)
    plt.hist(residuals, 20)
    plt.title("Histogram: residuals")
    plt.grid()

    plt.suptitle("Clock sync (stddev = {:.01f} m; max = {:.01f} m; "
                 "avg corr SNR: {:.01f} dB)"
                 .format(np.std(residuals) * s2m,
                         np.max(np.abs(residuals)) * s2m,
                         avg_snr_db))

    plt.tight_layout()
    plt.subplots_adjust(top=0.90) 
Example #27
Source File: SpectraKeras_CNN.py    From SpectralMachine with GNU General Public License v3.0 5 votes vote down vote up
def plotActivationsTrain(model):
    import matplotlib.pyplot as plt
    import tensorflow as tf
    dP = Conf()
    i = 0
    for layer in model.layers:
        if isinstance(layer, tf.keras.layers.Conv2D):
            weight_conv2d = layer.get_weights()[0][:,:,0,:]
            filter_index = 0
            col_size = dP.sizeColPlot
            row_size = int(dP.CL_filter[i]/dP.sizeColPlot)
            fig, ax = plt.subplots(row_size, col_size, figsize=(row_size*3,col_size*3))
                        
            for row in range(0,row_size):
                for col in range(0,col_size):
                    #ax[row][col].imshow(weight_conv2d_1[:,:,filter_index],cmap="gray")
                    ax[row][col].plot(weight_conv2d[:,:,filter_index][0])
                    filter_index += 1
            plt.suptitle("Training Conv2D_"+str(i)+" activations", fontsize=16)
            plt.savefig(dP.actPlotTrain+str(i)+".png", dpi = 160, format = 'png')  # Save plot
            print(" Saving conv2D activation plots in:", dP.actPlotTrain+str(i)+".png")
            i+=1
    
#************************************
# Plot Activations in Predictions
#************************************ 
Example #28
Source File: data.py    From cmocean with MIT License 5 votes vote down vote up
def show(cmap, var, vmin=None, vmax=None):
    '''Show a colormap for a chosen input variable var side by side with
    black and white and jet colormaps.

    :param cmap: Colormap instance
    :param var: Variable to plot.
    :param vmin=None: Min plot value.
    :param vmax=None: Max plot value.

    '''

    # get variable data
    lat, lon, z, data = read(var)

    fig = plt.figure(figsize=(16, 12))

    # Plot with grayscale
    ax = fig.add_subplot(3, 1, 1)
    map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with jet
    ax = fig.add_subplot(3, 1, 2)
    map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with cmap
    ax = fig.add_subplot(3, 1, 3)
    map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax)
    ax.set_xlabel('Longitude [degrees]')
    ax.set_ylabel('Depth [m]')
    plt.colorbar(map1, ax=ax)

    plt.suptitle(var) 
Example #29
Source File: viz.py    From Diffusion-Probabilistic-Models with MIT License 5 votes vote down vote up
def plot_parameter(theta_in, base_fname_part1, base_fname_part2="", title = '', n_colors=None):
    """
    Save both a raw and receptive field style plot of the contents of theta_in.
    base_fname_part1 provides the mandatory root of the filename.
    """

    theta = np.array(theta_in.copy()) # in case it was a scalar
    print "%s min %g median %g mean %g max %g shape"%(
        title, np.min(theta), np.median(theta), np.mean(theta), np.max(theta)), theta.shape
    theta = np.squeeze(theta)
    if len(theta.shape) == 0:
        # it's a scalar -- make it a 1d array
        theta = np.array([theta])
    shp = theta.shape
    if len(shp) > 2:
        theta = theta.reshape((theta.shape[0], -1))
        shp = theta.shape

    ## display basic figure
    plt.figure(figsize=[8,8])
    if len(shp) == 1:
        plt.plot(theta, '.', alpha=0.5)
    elif len(shp) == 2:
        plt.imshow(theta, interpolation='nearest', aspect='auto', cmap=cm.Greys_r)
        plt.colorbar()

    plt.title(title)
    plt.savefig(base_fname_part1 + '_raw_' + base_fname_part2 + '.pdf')
    plt.close()

    ## also display it in basis function view if it's a matrix, or
    ## if it's a bias with a square number of entries
    if len(shp) >= 2 or is_square(shp[0]):
        if len(shp) == 1:
            theta = theta.reshape((-1,1))
        plt.figure(figsize=[8,8])
        if show_receptive_fields(theta, n_colors=n_colors):
            plt.suptitle(title + "receptive fields")
            plt.savefig(base_fname_part1 + '_rf_' + base_fname_part2 + '.pdf')
        plt.close() 
Example #30
Source File: test_bbox_tight.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_bbox_inches_tight_suptile_legend():
    plt.plot(list(xrange(10)), label='a straight line')
    plt.legend(bbox_to_anchor=(0.9, 1), loc=2, )
    plt.title('Axis title')
    plt.suptitle('Figure title')

    # put an extra long y tick on to see that the bbox is accounted for
    def y_formatter(y, pos):
        if int(y) == 4:
            return 'The number 4'
        else:
            return str(y)
    plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))

    plt.xlabel('X axis')