传说被拯救 - Matplotlib

时间:2016-03-10 16:09:35

标签: python pdf matplotlib legend

我使用此代码绘制了多个子图:

f, axes = plt.subplots(7, 1, sharex='col', figsize=(13, 20))

for i in range(simulations):
    delta = numpy.zeros((simulations+samples, simulations+samples))
    data_x = ensamble_x + sample_x[i*100:(i*100)+100] 
    data_y = ensamble_y + sample_y[i*100:(i*100)+100] 
    for j in range(simulations+samples):
        for k in range(simulations+samples):
            if j <= k:
                dist = similarity_measure((data_x[j].flatten(), data_y[j].flatten()), (data_x[k].flatten(), data_y[k].flatten()))
                #delta[j, k] = delta[k, j] = numpy.mean(dist)

    model = manifold.TSNE(n_components=2, random_state=0)
    coords = model.fit_transform(delta)

    axes[i].scatter(coords[:100, 0], coords[:100, 1], marker='x', c=colors[i], s=50, edgecolor='None')
    axes[i].scatter(coords[100:, 0], coords[100:, 1], marker='o', c=colors, s=50, edgecolor='None')

    axes[i].set_title('Simulation '+str(i+1))

markers = []
labels = [str(n+1) for n in range(simulations)]
for i in range(simulations):
     markers.append(Line2D([0], [0], linestyle='None', marker="o", markersize=10, markeredgecolor="none", markerfacecolor=colors[i]))
plt.legend(markers, labels, numpoints=1, bbox_to_anchor=(1.0, -0.055), ncol=simulations) 
plt.tight_layout()
plt.savefig('Simulations.pdf', format='pdf')

产生类似这样的东西:

enter image description here

然而,保存的pdf正在切断传奇的一半。我试图更改figsize参数,但它不起作用。

如何强制在已保存的地块上包含图例?

我试过用:

markers = []
labels = [str(n+1) for n in range(simulations)]
for i in range(simulations):
     markers.append(Line2D([0], [0], linestyle='None', marker="o", markersize=10, markeredgecolor="none", markerfacecolor=colors[i]))
lgd = plt.legend(markers, labels, numpoints=1, bbox_to_anchor=(1.0, -0.055), ncol=simulations) 
plt.tight_layout()
plt.savefig('Simulations.pdf', bbox_extra_artists=(lgd,), format='pdf')

也没有成功。

2 个答案:

答案 0 :(得分:1)

尝试使用以下方法在子图下方添加一些额外空间:

f.subplots_adjust(bottom=0.2)

(调整0.2以满足您的需求)

答案 1 :(得分:1)

对我有用的是:

plt.savefig(file_path + '.pdf', format='pdf', bbox_extra_artists=(lgd,), bbox_inches='tight')

即,我必须在bbox_inches='tight'选项中插入savefig