def checkboxLegend(parent, *args, **kwargs): """ Creates a Legend with checkboxes to toggle visibility of all elements corresponding to entries in the legend Parameters ---------- parent : `~matplotlib.axes.Axes` or `.Figure` The artist that contains the legend. """ # get user genarated handler_map, and set handlelength to a default of 3 custom_handler_map = kwargs.get('handler_map', {}) if kwargs.get('handlelength', None) is None: kwargs['handlelength'] = 3 # update a default handler map to include user genarated handler_map hm = Legend.get_default_handler_map().copy() hm.update(custom_handler_map) # create interactive version of the new handler map for handler in hm: hm[handler] = VisibilityHandler( handler=Legend.get_legend_handler(hm, handler)) kwargs['handler_map'] = hm # return interactive legend return parent.legend(*args, **kwargs)
def test_path_collection(self): # Create a small scatter plot plot = plt.scatter([1, 2, 3], [2, 3, 4], c=[3, 4, 5], cmap=cmr.rainforest) # Add a cmap legend entry set_cmap_legend_entry(plot, 'Test') # Check if the plot now has a special handler assert plot in Legend.get_default_handler_map() # Create a legend plt.legend() # Close the plot plt.close()
def set_cmap_legend_entry(artist, label): """ Sets the label of the provided `artist` to `label`, and creates a legend entry using a miniature version of the colormap of `artist` as the legend icon. This function can be used to add legend entries for *MPL* artists that use a colormap, like those made with :func:`~matplotlib.pyplot.hexbin`; :func:`~matplotlib.pyplot.hist2d`; :func:`~matplotlib.pyplot.scatter`; or any :mod:`~matplotlib.pyplot` function that takes `cmap` as an input argument. Keep in mind that using this function will override any legend entry that already exists for `artist`. Parameters ---------- artist : :obj:`~matplotlib.artist.Artist` object Any artist object that has the `cmap` attribute, for which a legend entry must be made using its colormap as the icon. label : str The string that must be set as the label of `artist`. """ # Obtain the colormap of the provided artist cmap = getattr(artist, 'cmap', None) # If cmap is None, raise error if cmap is None: raise ValueError("Input argument 'artist' does not have attribute " "'cmap'!") # Set the label of this artist artist.set_label(label) # Add the HandlerColorPolyCollection to the default handler map for artist Legend.get_default_handler_map()[artist] = _HandlerColorPolyCollection()