How to use the matplotlib.pyplot.tight_layout 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 alsora / CNN_Visualization / caffeCNN_utils.py View on Github external
plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    np.set_printoptions(precision=2)

    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, np.around(cm[i, j], decimals=2),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True labels')
    plt.xlabel('Predicted labels')
    plt.savefig(title + ".png")

    return
github pnnl / socialsim / github-measurements / plots.py View on Github external
def plot_activity_timeline(data,xlabel,ylabel,title, log=False,loc=False):
    p = data
    for u in users:
        p[p['user'] == u]['value'].plot(legend=False,logy=False,label=u)

    plt.xticks(fontsize=15)
    plt.yticks(fontsize=15)
    plt.xlabel(xlabel, fontsize=20)
    plt.ylabel(ylabel, fontsize=20)
    plt.title(title, fontsize=20)
    plt.tight_layout()
    plt.xticks(rotation=45)
    if loc != False:
        savePlots(loc,plt)
        return 
    return plt.show()
github LittleHeap / MachineLearning-Algorithms / 7.Cluster / 7.1 kMeans.py View on Github external
x1_min, x2_min = np.min(data3, axis=0)
    x1_max, x2_max = np.max(data3, axis=0)
    x1_min, x1_max = expand(x1_min, x1_max)
    x2_min, x2_max = expand(x2_min, x2_max)
    plt.xlim((x1_min, x1_max))
    plt.ylim((x2_min, x2_max))
    plt.grid(True)

    plt.subplot(428)
    plt.title(u'数量不相等KMeans++聚类')
    plt.scatter(data3[:, 0], data3[:, 1], c=y3_hat, s=30, cmap=cm, edgecolors='none')
    plt.xlim((x1_min, x1_max))
    plt.ylim((x2_min, x2_max))
    plt.grid(True)

    plt.tight_layout(2)
    plt.suptitle(u'数据分布对KMeans聚类的影响', fontsize=18)
    # https://github.com/matplotlib/matplotlib/issues/829
    plt.subplots_adjust(top=0.92)
    plt.show()
github spyking-circus / spyking-circus-ort / benchmarks / scaling / electrodes / old / utils.py View on Github external
# Plot peak trains to compare them visually.
        plt.figure()
        # Plot generated peak train.
        x = [t for t in self.generated_peak_train]
        y = [0.0 for _ in x]
        plt.scatter(x, y, c='C1', marker='|')
        # Plot detected peak trains.
        detected_peak_trains = self.detected_peak_trains
        for k in range(0, self.nb_channels):
            x = [t for t in detected_peak_trains[k]]
            y = [float(k + 1) for _ in x]
            plt.scatter(x, y, c='C0', marker='|')
        plt.xlabel("time (arb. unit)")
        plt.ylabel("peak train")
        plt.title("Peak trains comparison")
        plt.tight_layout()
        plt.show()

        return
github PacktPublishing / Generative-Adversarial-Networks-Cookbook / Chapter4 / src / train.py View on Github external
def plot_check_batch(self,b,images):
        filename = "/data/batch_check_"+str(b)+".png"
        subplot_size = int(np.sqrt(images.shape[0]))
        plt.figure(figsize=(10,10))
        for i in range(images.shape[0]):
            plt.subplot(subplot_size, subplot_size, i+1)
            image = images[i, :, :, :]
            image = np.reshape(image, [self.H,self.W,self.C])
            plt.imshow(image)
            plt.axis('off')
        plt.tight_layout()
        plt.savefig(filename)
        plt.close('all')
        return
github gammapy / gammapy / gammapy / irf / psf_table.py View on Github external
def plot_exposure_vs_energy(self):
        """Plot exposure versus energy."""
        import matplotlib.pyplot as plt

        plt.figure(figsize=(4, 3))
        plt.plot(self.energy, self.exposure, color="black", lw=3)
        plt.semilogx()
        plt.xlabel("Energy (MeV)")
        plt.ylabel("Exposure (cm^2 s)")
        plt.xlim(1e4 / 1.3, 1.3 * 1e6)
        plt.ylim(0, 1.5e11)
        plt.tight_layout()
github Yagami360 / MachineLearning_Exercises_Python_scikit-learn / LogisticRegression_scikit-learn / main.py View on Github external
plt.bar(
        left = [0,1,2],
        height  = pre0[0]*100,
        tick_label = ["Setosa","Versicolor","Virginica"]
    )             
    plt.tight_layout()                  # グラフ同士のラベルが重ならない程度にグラフを小さくする。
    
    # 所属クラスの確率を棒グラフ表示(1,2)
    plt.subplot(2,2,2)  # plt.subplot(行数, 列数, 何番目のプロットか)
    plt.ylim( 0,100 )                   # y軸の範囲(0~100)
    plt.bar(
        left = [0,1,2],
        height  = pre1[0]*100,
        tick_label = ["Setosa","Versicolor","Virginica"]
    )             
    plt.tight_layout()                  # グラフ同士のラベルが重ならない程度にグラフを小さくする。

    # 所属クラスの確率を棒グラフ表示(2,1)
    plt.subplot(2,2,3)  # plt.subplot(行数, 列数, 何番目のプロットか)
    plt.ylim( 0,100 )                   # y軸の範囲(0~100)
    plt.bar(
        left = [0,1,2],
        height  = pre2[0]*100,
        tick_label = ["Setosa","Versicolor","Virginica"]
    )             
    plt.tight_layout()                  # グラフ同士のラベルが重ならない程度にグラフを小さくする。

    # 所属クラスの確率を棒グラフ表示(2,1)
    plt.subplot(2,2,4)  # plt.subplot(行数, 列数, 何番目のプロットか)
    plt.ylim( 0,100 )                   # y軸の範囲(0~100)
    plt.bar(
        left = [0,1,2],
github mathias-madsen / reinforce_tutorial / code / policies.py View on Github external
assert nblocks > 0

        ncols = int(np.ceil(np.sqrt(width/height * nblocks)))
        nrows = int(np.ceil(nblocks / ncols))
        ncols = nblocks if nrows == 1 else ncols

        figure = plt.figure(figsize=(width, height))

        for i, block in enumerate(blocks):
    
            plt.subplot(nrows, ncols, i + 1)
            plt.imshow(block, interpolation='nearest', aspect='auto')
            plt.colorbar()

        plt.tight_layout()

        if filename is not None:
            plt.savefig(filename)
        
        if show:
            plt.show()
        
        plt.close(figure)
github justindujardin / mathy / evaluate.py View on Github external
color="g",
        label="random",
    )

    diffs = "_".join(difficulties)
    title = f"agents_eval_{diffs}.png"
    plt.ylabel("Env")
    plt.xlabel("Win Percentage")
    plt.title(title)
    plt.yticks(index + bar_width * 2, labels)
    plt.legend()

    day_time = datetime.now().strftime("%Y_%m_%d_%H_%M")
    plt.savefig(f"images/{day_time}{title}.png", bbox_inches="tight")

    plt.tight_layout()
    plt.show()
github milankl / swm / plot / compare_energy_2runs.py View on Github external
##
expo = 1.   # stretching/squeezing for visualization

for v in ['mke','eke','mpe','epe','ke','pe']:
    D1[v] = (D1[v]/1e3)**expo       # from joule to kilojoule by /1e3
    D2[v] = (D2[v]/1e3)**expo

## PLOTTING   
levs=[]
for v in ['mke','eke','mpe','epe']:
    maxs = np.max((np.max(D1[v]),np.max(D2[v])))
    levs.append(np.linspace(0,maxs*0.95,64))

fig,axs = plt.subplots(2,4,figsize=(9,5),sharex=True,sharey=True)
plt.tight_layout(rect=[0,.08,1,0.98])
fig.subplots_adjust(wspace=0.03,hspace=0.03)
n = axs.shape[1]
caxs = [0,]*n
for i in range(n):
    pos = axs[-1,i].get_position()
    caxs[i] = fig.add_axes([pos.x0,0.11,pos.width,0.03])

qaxs = np.empty_like(axs)

tiks = [np.array([0,100,200,300]),np.array([0,100,200,300]),np.array([0,1,2,3,4,5]),np.array([0,1,2,3,4,5])]

qaxs[0,0] = axs[0,0].contourf(param1['x_T'],param1['y_T'],h2mat(D1['mke'],param1),levs[0],cmap=cm.thermal,extend='max')
cb1 = fig.colorbar(qaxs[0,0],cax=caxs[0],orientation='horizontal',ticks=tiks[0]**expo)
cb1.set_ticklabels(tiks[0])
cb1.set_label(r'[kJm$^{-2}$]')