Limit legend to visible data

with a slight correction from the code proposed by Justin, it works
fine (tested on mpl 1.0.1).

Is there a straightforward way to limit the legend only to lines that
appear within the current display limits? I have a plot that has too
many separate data series to show on the legend at once, but once I
zoom in it would be good to re-set the legend to show only the visible
data points/lines.


from matplotlib import transforms

def add_legend_viewlim(ax, **kwargs):
    """ Reset the legend in ax to only display lines that are
currently visible in plot area """
    label_objs = []
    label_texts = []
    ## print "viewLim:", ax.viewLim
    for line in ax.lines:
        line_label = line.get_label()
        if line.get_visible() and line_label and not line_label.startswith("_"):
            line_bbox = transforms.Bbox.unit()
            if ax.viewLim.overlaps(line_bbox):
                ## print line_label, line_bbox
    if label_objs:
        return ax.legend(label_objs, label_texts, **kwargs)
    elif ax.get_legend():


On Wed, Dec 1, 2010 at 11:58 AM, Justin McCann <jneilm@...83...> wrote:

peter butterworth