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

On Wed, Dec 1, 2010 at 11:58 AM, Justin McCann <jneilm@...> wrote:
> 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()
            line_bbox.update_from_data_xy(line.get_xydata())
            if ax.viewLim.overlaps(line_bbox):
                ## print line_label, line_bbox
                label_objs.append(line)
                label_texts.append(line_label)
    if label_objs:
        return ax.legend(label_objs, label_texts,  **kwargs)
    elif ax.get_legend():
        ax.get_legend().set_visible(False)


-- 
thanks,
peter butterworth

------------------------------------------------------------------------------
Special Offer-- Download ArcSight Logger for FREE (a $49 USD value)!
Finally, a world-class log management solution at an even better price-free!
Download using promo code Free_Logger_4_Dev2Dev. Offer expires 
February 28th, so secure your free ArcSight Logger TODAY! 
http://p.sf.net/sfu/arcsight-sfd2d
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users

Reply via email to