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