pceccon
pceccon

Reputation: 9844

Legend being cut off on saving - Matplotlib

I'm plot multiple subplots using this code:

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

Which generates something like this:

enter image description here

However, the saved pdf is cutting off half of the legend. I've tried to change the figsize parameter, but it didn't work.

How do I force the inclusion of the legend on the saved plot?

I've tried to use:

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

With no success too.

Upvotes: 2

Views: 5591

Answers (2)

pceccon
pceccon

Reputation: 9844

What worked for me was this:

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

I.e, I had to insert bbox_inches='tight' in the savefig options.

Upvotes: 5

tmdavison
tmdavison

Reputation: 69136

try adding some extra space below your subplots using:

f.subplots_adjust(bottom=0.2)

(adjust the 0.2 to suit your needs)

Upvotes: 1

Related Questions