Legend python

Legend python DEFAULT

Matplotlib.pyplot.legend() in Python

Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

Matplotlib.pyplot.legend()

A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes.

The attribute Loc in is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure.

The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has.It’s default value is 1.

Syntax:



matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)

The Following are some more attributes of function :

  • shadow: [None or bool] Whether to draw a shadow behind the legend.It’s Default value is None.
  • markerscale: [None or int or float] The relative size of legend markers compared with the originally drawn ones.The Default is None.
  • numpoints: [None or int] The number of marker points in the legend when creating a legend entry for a Line2D (line).The Default is None.
  • fontsize: The font size of the legend.If the value is numeric the size will be the absolute font size in points.
  • facecolor: [None or “inherit” or color] The legend’s background color.
  • edgecolor: [None or “inherit” or color] The legend’s background patch edge color.

Ways to use legend() function in Python –

Example 1:

Output :
graph

Example 2:

Output :
graph

Example 3:

Output :
graph

Example 4:

Output:

Example 5:

Output:
graph

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notesarrow_drop_up
Sours: https://www.geeksforgeeks.org/matplotlib-pyplot-legend-in-python/

Legend guide

Legend Handlers¶

In order to create legend entries, handles are given as an argument to an appropriate subclass. The choice of handler subclass is determined by the following rules:

  1. Update with the value in the keyword.
  2. Check if the is in the newly created .
  3. Check if the type of is in the newly created .
  4. Check if any of the types in the 's mro is in the newly created .

For completeness, this logic is mostly implemented in .

All of this flexibility means that we have the necessary hooks to implement custom handlers for our own type of legend key.

The simplest example of using custom handlers is to instantiate one of the existing subclasses. For the sake of simplicity, let's choose which accepts a numpoints argument (numpoints is also a keyword on the function for convenience). We can then pass the mapping of instance to Handler as a keyword to legend.

frommatplotlib.legend_handlerimportHandlerLine2Dline1,=plt.plot([3,2,1],marker='o',label='Line 1')line2,=plt.plot([1,2,3],marker='o',label='Line 2')plt.legend(handler_map={line1:HandlerLine2D(numpoints=4)})
legend guide

Out:

<matplotlib.legend.Legend object at 0x7fe64b59f4c0>

As you can see, "Line 1" now has 4 marker points, where "Line 2" has 2 (the default). Try the above code, only change the map's key from to . Notice how now both instances get 4 markers.

Along with handlers for complex plot types such as errorbars, stem plots and histograms, the default has a special handler () which simply plots the handles on top of one another for each item in the given tuple. The following example demonstrates combining two legend keys on top of one another:

fromnumpy.randomimportrandnz=randn(10)red_dot,=plt.plot(z,"ro",markersize=15)# Put a white cross over some of the data.white_cross,=plt.plot(z[:5],"w+",markeredgewidth=3,markersize=15)plt.legend([red_dot,(red_dot,white_cross)],["Attr A","Attr A+B"])
legend guide

Out:

<matplotlib.legend.Legend object at 0x7fe64a1a77f0>

The class can also be used to assign several legend keys to the same entry:

frommatplotlib.legend_handlerimportHandlerLine2D,HandlerTuplep1,=plt.plot([1,2.5,3],'r-d')p2,=plt.plot([3,2,1],'k-o')l=plt.legend([(p1,p2)],['Two keys'],numpoints=1,handler_map={tuple:HandlerTuple(ndivide=None)})
legend guide

Implementing a custom legend handler¶

A custom handler can be implemented to turn any handle into a legend key (handles don't necessarily need to be matplotlib artists). The handler must implement a method which returns a single artist for the legend to use. The required signature for is documented at .

importmatplotlib.patchesasmpatchesclassAnyObject:passclassAnyObjectHandler:deflegend_artist(self,legend,orig_handle,fontsize,handlebox):x0,y0=handlebox.xdescent,handlebox.ydescentwidth,height=handlebox.width,handlebox.heightpatch=mpatches.Rectangle([x0,y0],width,height,facecolor='red',edgecolor='black',hatch='xx',lw=3,transform=handlebox.get_transform())handlebox.add_artist(patch)returnpatchplt.legend([AnyObject()],['My first handler'],handler_map={AnyObject:AnyObjectHandler()})
legend guide

Out:

<matplotlib.legend.Legend object at 0x7fe64b8bc2b0>

Alternatively, had we wanted to globally accept instances without needing to manually set the handler_map keyword all the time, we could have registered the new handler with:

frommatplotlib.legendimportLegendLegend.update_default_handler_map({AnyObject:AnyObjectHandler()})

Whilst the power here is clear, remember that there are already many handlers implemented and what you want to achieve may already be easily possible with existing classes. For example, to produce elliptical legend keys, rather than rectangular ones:

frommatplotlib.legend_handlerimportHandlerPatchclassHandlerEllipse(HandlerPatch):defcreate_artists(self,legend,orig_handle,xdescent,ydescent,width,height,fontsize,trans):center=0.5*width-0.5*xdescent,0.5*height-0.5*ydescentp=mpatches.Ellipse(xy=center,width=width+xdescent,height=height+ydescent)self.update_prop(p,orig_handle,legend)p.set_transform(trans)return[p]c=mpatches.Circle((0.5,0.5),0.25,facecolor="green",edgecolor="red",linewidth=3)plt.gca().add_patch(c)plt.legend([c],["An ellipse, not a rectangle"],handler_map={mpatches.Circle:HandlerEllipse()})
legend guide

Out:

<matplotlib.legend.Legend object at 0x7fe64b68e0d0>

Total running time of the script: ( 0 minutes 2.851 seconds)

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery

Sours: https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html
  1. Animal get well cards
  2. Flower knitting loom
  3. Ukiah to chico
  4. Cleveland tx weather

How to Add Legend to Scatterplot Colored by a Variable with Matplotlib in Python

Matplotlib, one of the powerful Python graphics library, has many way to add colors to a scatter plot and specify legend. Earlier we saw a tutorial, how to add colors to data points in a scatter plot made with Matplotlib‘s scatter() function. In this tutorial, we will learn how to add right legend to a scatter plot colored by a variable that is part of the data.

Let us load Pandas and Matplotlib’s pyplot.

import pandas as pd import matplotlib.pyplot as plt

We will use Palmer penguins data for making the scatter plot. We have the penguins data on datavizpyr.com’s github page.

penguins_data="https://raw.githubusercontent.com/datavizpyr/data/master/palmer_penguin_species.tsv" # load penguns data with Pandas read_csv df = pd.read_csv(penguins_data, sep="\t")

Here we remove any missing data using Pandas’ dropna() function.

df = df.dropna() df.head() species island culmen_length_mm culmen_depth_mm flipper_length_mm body_mass_g sex 0 Adelie Torgersen 39.1 18.7 181.0 3750.0 MALE 1 Adelie Torgersen 39.5 17.4 186.0 3800.0 FEMALE 2 Adelie Torgersen 40.3 18.0 195.0 3250.0 FEMALE 4 Adelie Torgersen 36.7 19.3 193.0 3450.0 FEMALE 5 Adelie Torgersen 39.3 20.6 190.0 3650.0 MALE

First, let us get started by making a scatterplot using Matplotlib’s scatter function. We use “c” argument in scatter() function to color data points by species variable in the dataframe.

plt.figure(figsize=(8,6)) plt.scatter(df.culmen_length_mm, df.culmen_depth_mm, s=150, c=df.species.astype('category').cat.codes) plt.xlabel("Culmen Length", size=24) plt.ylabel("Culmen Depth", size=24) plt.savefig("scatterplot_point_colored_by_variable_matplotlib_Python.png", format='png',dpi=150)

Note that the scatter plot colored by a variable is missing legend to describe the meaning of the clusters we see.

Add Color to Scatterplot by variable in Matplotlib

Adding legend to Matplotlib scatte plot

We can try to add legend to the scatterplot colored by a variable, by using legend() function in Matplotlib. In legend(), we specify title and handles by extracting legend elements from the plot.

plt.figure(figsize=(8,6)) scatter = plt.scatter(df.culmen_length_mm, df.culmen_depth_mm, s=150, c=df.species.astype('category').cat.codes) plt.xlabel("Culmen Length", size=24) plt.ylabel("Culmen Depth", size=24) # add legend to the plot with names plt.legend(handles=scatter.legend_elements()[0], title="species") plt.savefig("scatterplot_colored_by_variable_legend_first_try_matplotlib_Python.png", format='png',dpi=150)

Our first attempt to add legends did not work well. We can see that we have a legend with colors but not the variable names.

First try to add legend to scatterplot matplotlib

We did not get legend labels mainly because, we colored the scatterplot using numerical code for the species variable. Note, we use “df.species.astype(‘category’).cat.codes” to color the data points.

We can maually specify labels for legend using Matplotlib’s legend() function’s argument “labels”. We define labels using a list of species names first.

plt.figure(figsize=(8,6)) sp_names = ['Adelie', 'Gentoo', 'Chinstrap'] scatter = plt.scatter(df.culmen_length_mm, df.culmen_depth_mm, s=150, c=df.species.astype('category').cat.codes) plt.xlabel("Culmen Length", size=24) plt.ylabel("Culmen Depth", size=24) # add legend to the plot with names plt.legend(handles=scatter.legend_elements()[0], labels=sp_names, title="species") plt.savefig("scatterplot_colored_by_variable_with_legend_matplotlib_Python.png", format='png',dpi=150)

Now we have legend for scatterplot colored by a variable.

Matplotlib Scatter plot with legend

Filed Under: Matplotlib, Matplotlib scatterplot legend, PythonTagged With: Matplotlib, Python

Sours: https://datavizpyr.com/add-legend-to-scatterplot-colored-by-a-variable-with-matplotlib-in-python/
Python Matplotlib Legend

matplotlib.pyplot.legend

Other Parameters:
locstr or pair of floats, default: (default: ) ('best' for axes, 'upper right' for figures)

The location of the legend.

The strings place the legend at the corresponding corner of the axes/figure.

The strings place the legend at the center of the corresponding edge of the axes/figure.

The string places the legend at the center of the axes/figure.

The string places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

For back-compatibility, (but no other location) can also be spelled , and each "string" locations can also be given as a numeric value:

Location StringLocation Code
'best'0
'upper right'1
'upper left'2
'lower left'3
'lower right'4
'right'5
'center left'6
'center right'7
'lower center'8
'upper center'9
'center'10
bbox_to_anchor, 2-tuple, or 4-tuple of floats

Box that is used to position the legend in conjunction with loc. Defaults to (if called as a method to ) or (if ). This argument allows arbitrary placement of the legend.

Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which is called.

If a 4-tuple or is given, then it specifies the bbox that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):

loc='best',bbox_to_anchor=(0.5,0.,0.5,0.5)

A 2-tuple places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used:

loc='upper right',bbox_to_anchor=(0.5,0.5)
ncolint, default: 1

The number of columns that the legend has.

propNone or or dict

The font properties of the legend. If None (default), the current will be used.

fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.

labelcolorstr or list

The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').

numpointsint, default: (default: )

The number of marker points in the legend when creating a legend entry for a (line).

scatterpointsint, default: (default: )

The number of marker points in the legend when creating a legend entry for a (scatter plot).

scatteryoffsetsiterable of floats, default:

The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to .

markerscalefloat, default: (default: )

The relative size of legend markers compared with the originally drawn ones.

markerfirstbool, default: True

If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.

frameonbool, default: (default: )

Whether the legend should be drawn on a patch (frame).

fancyboxbool, default: (default: )

Whether round edges should be enabled around the which makes up the legend's background.

shadowbool, default: (default: )

Whether to draw a shadow behind the legend.

framealphafloat, default: (default: )

The alpha transparency of the legend's background. If shadow is activated and framealpha is , the default value is ignored.

facecolor"inherit" or color, default: (default: )

The legend's background color. If , use (default: ).

edgecolor"inherit" or color, default: (default: )

The legend's background patch edge color. If , use take (default: ).

mode{"expand", None}

If mode is set to the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).

bbox_transformNone or

The transform for the bounding box (bbox_to_anchor). For a value of (default) the Axes' transform will be used.

titlestr or None

The legend's title. Default is no title ().

title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: (default: )

The font size of the legend's title.

borderpadfloat, default: (default: )

The fractional whitespace inside the legend border, in font-size units.

labelspacingfloat, default: (default: )

The vertical space between the legend entries, in font-size units.

handlelengthfloat, default: (default: )

The length of the legend handles, in font-size units.

handletextpadfloat, default: (default: )

The pad between the legend handle and text, in font-size units.

borderaxespadfloat, default: (default: )

The pad between the axes and legend border, in font-size units.

columnspacingfloat, default: (default: )

The spacing between columns, in font-size units.

handler_mapdict or None

The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at .

Sours: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html

Python legend

.

QGIS Python (PyQGIS) - Add legend and scalebar to map layout

.

You will also like:

.



271 272 273 274 275