【问题标题】:Legend being cut off on saving - Matplotlib图例在保存时被切断 - Matplotlib
【发布时间】:2016-03-10 16:09:34
【问题描述】:

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

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')

它会生成这样的东西:

但是,保存下来的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')

也没有成功。

【问题讨论】:

    标签: python pdf matplotlib legend


    【解决方案1】:

    对我有用的是:

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

    也就是说,我必须在 savefig 选项中插入 bbox_inches='tight'

    【讨论】:

      【解决方案2】:

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

      f.subplots_adjust(bottom=0.2)
      

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

      【讨论】:

        猜你喜欢
        • 2023-02-24
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多