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