Is there a way to put the legend for a graph inside the margin instead of on the graph, in other words to put the legend where excel would? I have a stacked bar graph with many categories and so the legend is vary large and there is little dead space on the graph. As a result if the legend is on the graph it covers up one of the bars.

# Adding a Legend

Is there a way to put the legend for a graph inside the margin instead

of on the graph, in other words to put the legend where excel would?

Look into either “figlegend” or the “bbox_to_anchor” keyword argument to “legend”. You can use either of these to place the legend outside of the axis boundaries. However, this won’t resize the original axes.

Sometimes, it’s easier to just make a new, separate axis for the legend, and resize the original axis. This is easily done with the axes_grid toolkit. E.g.:

import matplotlib.pyplot as plt

from matplotlib import cm

import numpy as np

from mpl_toolkits.axes_grid1 import make_axes_locatable

## Make some data

data = np.random.random(10)

x = np.arange(data.size)

colors = cm.jet(x.astype(np.float) / x.size)

names = [repr(i) for i in range(data.size)]

## Basic bar plot

fig = plt.figure()

ax = fig.add_subplot(111)

bars = ax.bar(x, data, color=colors)

## Now make a new axis for the legend that takes up 10% of the width…

divider = make_axes_locatable(ax)

legend_ax = divider.append_axes(‘right’, ‘10%’)

legend_ax.axis(‘off’)

## Now make the legend on the new axis

legend_ax.legend(bars, names, mode=‘expand’, frameon=False)

plt.show()

Hope that helps!

-Joe

## ···

On Sun, Sep 19, 2010 at 10:40 PM, Kelson Zawack <zawackkfb@…83…3055…> wrote: