user8200327
user8200327

Reputation:

Matplotlib legend too wide

I am plotting a graph with six curves, where each curve has a label. The legend is placed below the graph, but it's wider than the figure. Please see code and screenshot.

#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(6):
    ax.plot(x, i * x, label='long_long_name = %ix$' % i)

#ax.legend()
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
              fancybox=True, shadow=True, ncol=3)
fig.tight_layout(rect=[0, 0.1, 1, 0.95])
plt.show()

How to configure the proper graph and legend size/position? I looked at Legend Guide and this post, but couldn't figure out how to make the legend narrower.

Upvotes: 1

Views: 5291

Answers (1)

I would simply recommend you change either the legend font size or the plot figure size. For doing so:

fig = plt.figure(figsize=(x_size, y_size))

Try using x_size = 8 and y_size = 5.

Or

ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=3, fontsize = size)

Try using size = 8.

Upvotes: 2

Related Questions