@@ -877,6 +877,7 @@ def draw(self, renderer):
877
877
class PathCollection (_CollectionWithSizes ):
878
878
"""
879
879
This is the most basic :class:`Collection` subclass.
880
+ A :class:`PathCollection` is e.g. created by a :meth:`~.Axes.scatter` plot.
880
881
"""
881
882
@docstring .dedent_interpd
882
883
def __init__ (self , paths , sizes = None , ** kwargs ):
@@ -899,6 +900,126 @@ def set_paths(self, paths):
899
900
def get_paths (self ):
900
901
return self ._paths
901
902
903
+ def legend_elements (self , prop = "colors" , num = "auto" ,
904
+ fmt = None , func = lambda x : x , ** kwargs ):
905
+ """
906
+ Creates legend handles and labels for a PathCollection. This is useful
907
+ for obtaining a legend for a :meth:`~.Axes.scatter` plot. E.g.::
908
+
909
+ scatter = plt.scatter([1,2,3], [4,5,6], c=[7,2,3])
910
+ plt.legend(*scatter.legend_elements())
911
+
912
+ Also see the :ref:`automatedlegendcreation` example.
913
+
914
+ Parameters
915
+ ----------
916
+ prop : string, optional, default *"colors"*
917
+ Can be *"colors"* or *"sizes"*. In case of *"colors"*, the legend
918
+ handles will show the different colors of the collection. In case
919
+ of "sizes", the legend will show the different sizes.
920
+ num : int or None or string "auto", or `~.ticker.Locator`, optional
921
+ (default "auto")
922
+ Target number of elements to create.
923
+ If None, use all unique elements of the mappable array. If an
924
+ integer, target to use *num* elements in the normed range.
925
+ If *"auto"*, try to determine which option better suits the nature
926
+ of the data.
927
+ The number of created elements may slightly deviate from *num* due
928
+ to a `~.ticker.Locator` being used to find useful locations.
929
+ Finally, a `~.ticker.Locator` can be provided.
930
+ fmt : string, `~matplotlib.ticker.Formatter`, or None (default)
931
+ The format or formatter to use for the labels. If a string must be
932
+ a valid input for a `~.StrMethodFormatter`. If None (the default),
933
+ use a `~.ScalarFormatter`.
934
+ func : function, default *lambda x: x*
935
+ Function to calculate the labels. Often the size (or color)
936
+ argument to :meth:`~.Axes.scatter` will have been pre-processed
937
+ by the user using a function *s = f(x)* to make the markers
938
+ visible; e.g. *size = np.log10(x)*. Providing the inverse of this
939
+ function here allows that pre-processing to be inverted, so that
940
+ the legend labels have the correct values;
941
+ e.g. *func = np.exp(x, 10)*.
942
+ kwargs : further parameters
943
+ Allowed kwargs are *color* and *size*. E.g. it may be useful to
944
+ set the color of the markers if *prop="sizes"* is used; similarly
945
+ to set the size of the markers if *prop="colors"* is used.
946
+ Any further parameters are passed onto the `.Line2D` instance.
947
+ This may be useful to e.g. specify a different *markeredgecolor* or
948
+ *alpha* for the legend handles.
949
+
950
+ Returns
951
+ -------
952
+ tuple (handles, labels)
953
+ with *handles* being a list of `.Line2D` objects
954
+ and *labels* a list of strings of the same length.
955
+ """
956
+ handles = []
957
+ labels = []
958
+ hasarray = self .get_array () is not None
959
+ if fmt is None :
960
+ fmt = mpl .ticker .ScalarFormatter (useOffset = False , useMathText = True )
961
+ elif type (fmt ) == str :
962
+ fmt = mpl .ticker .StrMethodFormatter (fmt )
963
+ fmt .create_dummy_axis ()
964
+
965
+ if prop == "colors" and hasarray :
966
+ u = np .unique (self .get_array ())
967
+ size = kwargs .pop ("size" , mpl .rcParams ["lines.markersize" ])
968
+ elif prop == "sizes" :
969
+ u = np .unique (self .get_sizes ())
970
+ color = kwargs .pop ("color" , "k" )
971
+ else :
972
+ warnings .warn ("Invalid prop provided, or collection without "
973
+ "array used." )
974
+ return handles , labels
975
+
976
+ fmt .set_bounds (func (u ).min (), func (u ).max ())
977
+ if num == "auto" :
978
+ num = 9
979
+ if len (u ) <= num :
980
+ num = None
981
+ if num is None :
982
+ values = u
983
+ label_values = func (values )
984
+ else :
985
+ if prop == "colors" and hasarray :
986
+ arr = self .get_array ()
987
+ elif prop == "sizes" :
988
+ arr = self .get_sizes ()
989
+ if isinstance (num , mpl .ticker .Locator ):
990
+ loc = num
991
+ else :
992
+ num = int (num )
993
+ loc = mpl .ticker .MaxNLocator (nbins = num , min_n_ticks = num - 1 ,
994
+ steps = [1 , 2 , 2.5 , 3 , 5 , 6 , 8 , 10 ])
995
+ label_values = loc .tick_values (func (arr ).min (), func (arr ).max ())
996
+ cond = (label_values >= func (arr ).min ()) & \
997
+ (label_values <= func (arr ).max ())
998
+ label_values = label_values [cond ]
999
+ xarr = np .linspace (arr .min (), arr .max (), 256 )
1000
+ values = np .interp (label_values , func (xarr ), xarr )
1001
+
1002
+ kw = dict (markeredgewidth = self .get_linewidths ()[0 ],
1003
+ alpha = self .get_alpha ())
1004
+ kw .update (kwargs )
1005
+
1006
+ for val , lab in zip (values , label_values ):
1007
+ if prop == "colors" and hasarray :
1008
+ color = self .cmap (self .norm (val ))
1009
+ elif prop == "sizes" :
1010
+ size = np .sqrt (val )
1011
+ if np .isclose (size , 0.0 ):
1012
+ continue
1013
+ h = mlines .Line2D ([0 ], [0 ], ls = "" , color = color , ms = size ,
1014
+ marker = self .get_paths ()[0 ], ** kw )
1015
+ handles .append (h )
1016
+ if hasattr (fmt , "set_locs" ):
1017
+ fmt .set_locs (label_values )
1018
+ l = fmt (lab )
1019
+ labels .append (l )
1020
+
1021
+ return handles , labels
1022
+
902
1023
903
1024
class PolyCollection (_CollectionWithSizes ):
904
1025
@docstring .dedent_interpd
0 commit comments