Plt legend location

Plt legend location DEFAULT

“python legend position” Code Answer’s

legend size matplotlib







Add a Grepper Answer

Python answers related to “python legend position”

Python queries related to “python legend position”

Browse Python Answers by Framework

More “Kinda” Related Python Answers View All Python Answers »

  • sns.boxplot code
  • matplotlib axis labels
  • python plot axis labels
  • axis labels python
  • add vertical line in plot python
  • 3d plot
  • bar chart in python
  • sns time series plot
  • ipywidgets label text color
  • markers seaborn
  • add rectangle matplotlib
  • how to get current latitude and longitude in python
  • change marker border color plotly
  • pyplot new figure
  • matlab filter in python
  • legend for pie chart matplotlib
  • plt multiple figures to show
  • open multiple plots python
  • plot pandas series with matplotlib
  • numpy image histogram plot
  • plt.hist bins
  • matplotlib.pyplot.polar() Function
  • mean =[0,0] covariance = [[1,0],[0,100]] ds = np.random.multivariate_normal(mean,covariance,500) dframe = pd.DataFrame(ds, columns=['col1', 'col2']) fig = sns.kdeplot(dframe).get_figure() fig.savefig('kde1.png')
  • seaborn countplot hue stacked
  • seaborn orient
  • matplotlib tick label position left and right x axis
  • sns color specific points
  • how to overlap two barplots in seaborn
  • matplotlib limit number of ticks
  • normalize a group in countplot
  • pyplot x vs y
  • figure in matplotlib
  • add legend to colorbar
  • violin plot python
  • subplot figure size
  • charts in python
  • dfs graph
  • 3d graph python
  • color plt
  • grid off matplotlib
  • pyplot.plot
  • cmap seaborn
  • pylatex add section without numbering
  • remove spines and ticks from graph
  • matplotlib remove drawn text
  • pyplot histogram labels in center
  • ORing two cv mat objects
  • turn off subplot
  • Bar Charts bokeh
  • matplotlib x tlabels ax.set_xlabel
  • add sign to y axis values python
  • sns.distplot fit
  • how to make a scatter plot matrix iris flower dataset
  • python invert colormap
  • change graph size
  • plt.savefig cutting off labels
  • Matplotlib inside Jupyter | Jupyter generate graphs.
  • how to make a dashboard with data representation using python free dash
  • python set grid thickness
  • seaborn documentation x axis range
  • python align label left
  • matplotlib colorbar reverse direction
  • convert hex rgb to matplotlib color
  • plotly table cell color based on values
  • create graph, x y axis | graph plotting
  • python save .mat
  • matplot lib mehrere bilder nebeneinander
  • matplotlib text relative to axis
  • how to make reportlab table header bold in python
  • distplot in python
  • add colorbar to 2d hist
  • graph bokeh
  • z transform in python
  • ticklabels are not centered heatmap
  • matplotlib despine
  • draw networkx graph using plt.pause
  • To visualize the correlation between any two columns | scatter plot graph
  • python graphviz undirected graph
  • remove exponent pandas plot
  • plot a against b
  • how to highlight cell in openpyxl
  • Change Separator Value When Printing
  • networkx draw graph with weight
  • cheat sheet python
  • x y coordinates in python
  • how to discover which index labels are in other
  • how to prevent \textbackslash in LaTeX from Python
  • pylatex bold
  • matp[lotlib max y value
  • show only lower diagonal in sns pairplot
  • Seaborn boxplots shifted incorrectly along x-axis
  • matplotlib x axis at the top
  • python label lines in plot
  • how to show line chart in seaborn lib
  • "slide_layouts[2]" pptx python
  • python matplotlib pyplot set axis equals
  • pandas subplots
  • python plot map with geolocation arrays
  • matplotlib object oriented
  • math plotlib 2 y axes
  • introduction python graphviz simple graph examples
  • matplotlib FiveThirtyEight horizontal graph
  • show avg value in sns boxplot
  • how to display text on boxplot in python
  • stacked bar chart
  • Wireframes and Surface Plots
  • how to draw threshold line in bar graph python
  • does the axis tell you pupillary distance
  • Overlapping xtick labels pyplot
  • advacned go scatter plot
  • axes turn of axis matplotlb
  • plt.plot(x, softmax(scores).T, linewidth=2)
  • controlliing a fill pattern in matplotlib
  • save matplotlib figure as array
  • hide some hours plotly
  • equivalent of geom smooth function in python using plotline lib
  • scatter plot in python stack overflow
  • matplotlib savefig legend cut off
  • python cmd plot
  • left-align the y-tick labels | remove the current labels
  • jupyter notebook fancy print cross tab
  • Python colorbar for circular heatmap
  • plt clor image histogram
  • pyplot set x range
  • historicaltickbidask
  • curve multiple viarable curve fit python book
  • python convert latitude longitude to x y
  • seaborn dot plot hue
  • pandas grid subplots
  • r value on poly fit python
  • matplotlib piechart show small groups as others
  • cairo.context transform vertical text python
  • plot every nth label in barplot
  • matplotlib bring plot to front in plots with twin axis
  • opencv houghlines only horizontal
  • xlabel font type matplotlib
  • reportlab line thickness
  • scree plot sklearn
  • qq plot using seaborn
  • `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
  • clustermap subplots
  • add vertical line to horizontal graph
  • remove grid from 3d plots
  • import matplotlib submodule 'style'
  • label default text value python
  • How to Set Axis Range (xlim, ylim) in Matplotlib
  • show percentage in seaborn countplot
  • matplotlib doesnt show suptitle
  • pyplot define plotsize
  • scree plot python
  • how to plot pareto chart in python
  • matplotlib FiveThirtyEight adding y-tick labels
  • matplotlib transform data units to pixel units
  • change size of yticks python
  • vscode python region folding
  • iris data pandas scatterplot
  • matplotlib twinx legend
  • python colorama
  • how to plot side by side bar horizontal bar graph in python
  • qq plot using seaborn with regression line
  • pandas seaborn distplot
  • matplotlib bar graph print first n values
  • pandas plot column titles vertical
  • multiclass.roc plot title
  • restrict ticks to integers matplotlib
  • jupiter lab
  • pie chart add outline python
  • jupyter_ascending
  • axis label in Bokeh
  • table and amorization charts using tkinter
  • scatter plot actual vs predicted python
  • matplotlib removing ticks and spines
  • gtk label set label
  • set colour to inserplaintext qtextedit in python
  • python plot auc 95% confidence intervals stackoverflow
  • import csv in dash for graph
  • how to make a plt plot for na image bigger
  • import matplotlib sub
  • matplotlib FiveThirtyEight creating a signature
  • Multiples placeholders in python Formatters
  • grouped box plot in python
  • matplotlib grid in background
  • python plot draw the goal line
  • what is tf.linalg.band_part?
  • xlabel not showing matplotlib
  • python create a grid of points
  • subplots
  • thicker lines in colorbar for contourplot
  • matplotlib draw line x1, y1
  • plotly polyline map
  • matplotlib create histogram edge color
  • find each geometry overlap python
  • plotly backend pandas
  • add x=y line to scatter plot python
  • bar chart with x-ticks
  • pandas line plot dictionary
  • matplotlib draw line between subplots
  • def get_label(Dir): for nextdir in os.listdir(Dir): if not nextdir.startswith('.'): if nextdir in ['NORMAL']: label = 0 elif nextdir in ['PNEUMONIA']: label = 1 else: label = 2 return nextdir, label
  • how to give order in boxplot matplotlib
  • label binarizer
  • pyhton how to chnge colour of graphs
  • axes increase fonsize of values python
  • Generate seaborn plot.
  • mechanize python fill
  • change text color in jupyter notebook
  • pie chart maptlotlib larger labels
  • df.fillna("tagline",inplace=True) in jupyter notebook
  • python dash plotly scatter draw a circle on the map
  • default orange and blue matplotlib
  • matplotlib transparency
  • matplotlib set dpi 300
  • plot idl
  • matplotlib rotate text box
  • couple legend from twin axes python
  • make large 3d plot in python
  • how to add percentage in countplot
  • rotate existing labels python
  • season plot with cartopy in python
  • how to plot a correlation matrix seaborn
  • plt.tight_layout() cuts x axis
  • two labels on one axis python
  • python excel zelle schreiben
  • pyplot common labels
  • plt.text background alpha
  • how to remove no data times plotly
  • python make label display multiple lines
  • newspaper pypi
  • graph outlier detection
  • matplotlib pie chart move autotext
  • biquadratic curve fitting python
  • plotly facet_grid python
  • figure vs plot matplotlib
  • dont squeeze plot when creating colorbar matplotlib
  • jupyter notebook don't show plot
  • check labels with handles in ax
  • python tkinter plot points
  • make sns heatmap colorbar larger
  • create series with number intervals
  • legend matplotlib twinx
  • Modifiying line plots
  • 'FigureWidget' object has no attribute 'on_selection'
  • adding text on barplot using seabron
  • matplotlib legend multiple columns
  • matplotlib include first number in plotter
  • matplotlib FiveThirtyEight style graph
  • network graph bokeh
  • python svg viewing
  • matplolib histogramme
  • networkx draw labels
  • increase colorbar ticksize
  • pandas series draw distribution
  • Overlay GoogleMaps in Dash-Plotly
  • Location of matploitlibrc file
  • inverse box-cox transformation python
  • Google tuner
  • ax text relative coordinates
  • matplotlib figure size not working
  • Matplotlib add text to axes
  • matplotlib bar3d
  • xtick for axvline
  • legend outside subplot not displayed
  • jupyterlab interactive plot
  • seaborn heatmap x labels horizontal
  • matplotlib display graph on jupyter notebook
  • Generate bar plot python
  • how to use ggplot matplotlib
  • Python scatter with histogram
  • pls work
  • pandas plot hide object type
  • Horizontal bar graph OO interface
  • tick size colorbar python
  • increase pie chart size python
  • Changing default fonts in matploitlibrc file
  • bar plot bokeh
  • seaborn heatmap center xticks
  • jupyter notebook do not show matplotlib text above plot
  • two legend left and right x asix matplotlib
  • matplotlib ax.annotate color of the arrow
  • mask and then fillna
  • Grouped bar chart with labels
  • matplotlig adding progress bar
  • axes color python
  • how to plot an array in python
  • matplotlib plt.sapect
  • pls help i need tkintwr help plspslspslspsl help tkinter
  • draw a marker in basemap python
  • reportlab python add font style
  • Separating a relational plot based on a sixth variable | seaborn relational plot
  • xlabel font size python latex
  • add title to relplot seaborn
  • pyspark reduce a list
  • add colorbar to figure matplotlib line plots
  • change markersize in legend matplotlib
  • how can i plot graph from 2 dataframes in same window python
  • how to define the range of values in seaborn heatmap
  • boxplot code
  • python plot heatmap by city
  • bokeh bar chart
  • plot matplotlib size
  • matplotlib custom ticks
  • label axis matplotlib
  • add caption to plot python
  • python plt show legend
  • what is seaborn in python
  • fig=plt.figure(figsize=(2,2))
  • plot time series python
  • matplotlib set colorbar range
  • plotly write html
  • add colorbar matplotlib
  • matplotlib units of scatter size
  • jupyter notebook plot background dark theme
  • axes_style seaborn
  • python scatter size
  • significant figures on axes plot matplotlib
  • add border to table in python pptx
  • python seaborn violin stack overflow
  • matplotlib get padding from bbox
  • cumulative chart python plotly
  • hide and show line in bokeh legend
  • make a effective figure in python
  • # Plot the histogram of 'sex' attribute using Matplotlib # Use bins = 2 and rwidth = 0.85
  • networkx - remove small components from a graph
  • how to add twoo segmen time series in a single plot
  • metin2dev python grid position
  • Highlighting the shortest path in a Networkx graph
  • module 'matplotlib' has no attribute 'xlabel'
  • markers are not visible on line plot
  • spider chart in python using
  • medium seaaborn mathplot diesign styles
  • lines =
  • mostrare i grafici matplotlib sulla shell python
  • change group box title font size
  • change background color of tkinter
  • pandas shuffle rows
  • how to get unix timestamp in python
  • how to save matplotlib figure to png
  • python round up
  • python loop through list
  • command errored out with exit status 1:
  • if else ptyon
  • python iterate through dictionary
  • slack send message python
  • python text fromatting rows
  • python find index by value
  • how to make a python list
  • flask for loops
  • print multiple lines python
  • how to make a class in python
  • how to get the remainder in python
  • python add one
  • how to delete an item from a list python
  • how to import matplotlib in python
  • how to execute bash commands in python script
  • if list item in string python
  • python 3 slice reverse
  • python unexpected eof while parsing
  • how to install python libraries using pip
  • how to check django version
  • python startswith
  • how to replace first line of a textfile python
  • sorting python array
  • python how to align text writen to a file
  • scrapy itemloader example
  • if a specific column name is present drop tyhe column
  • F-Strings decilamal places
  • Young C so new(pro.cashmoneyap x nazz music) soundcloud

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


<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


<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


<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:


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


<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

  1. Yz125 cone pipe
  2. Public domain christmas clipart
  3. Oil bond home depot

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.


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.

 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

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.


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 :

Example 2:

Output :

Example 3:

Output :

Example 4:


Example 5:


My Personal Notesarrow_drop_up


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
'upper right'1
'upper left'2
'lower left'3
'lower right'4
'center left'6
'center right'7
'lower center'8
'upper center'9
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):


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 .


Location plt legend

Matplotlib Examples: Displaying and Configuring Legends

Last updated:

Table of Contents

Confused about pyplot and matplotlib? See Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?

All examples assume you're working on the pyplot interface.

All code is available online on this jupyter notebook

Add legend to plot

Call .

Note that the argument is a list of legends. Pass a list with a single element to have a single legend:

simplest-possible-example-add-legend-to-matplotlib-plotCall plt.legend() with a list of legends as arguments.
This is the simplest possible use case.

Add legend to multiple plots in the same axis

While you can just pass a list with multiple texts to plt.legend(), it's better to label each plot individually so there are no errors.

  • 1) Add a parameter to each plot.

  • 2) Call with no parameters

legend-for-multiple-plots-matplotlibEach line plot gets its own legend

Add legend to single axis

For more info on how to plot multiple plots in the same Figure, see Matplotlib Subplots: Best Practices and Examples

If there are multiple axes on your plot, you can add legends to a single axis if you wish.

add-legend-to-single-axesOnly the last axes has had a legend set

Change legend location

If you don't provide a location for the legend, matplotlib tries to figure out by itself where it should place it.

To force another location, set parameter using location a string (e.g. 'upper left' or 'lower right') as argument.

set legend sizeOther values for include 'upper right', 'upper left', 'lower center',
'lower right' and 'best' (this is the default
value, matplotlib tries to figure out where to place it).

Disable legend

this must be AFTER the call to plot

Some libraries such as Pandas default to setting legends in plots.

So if legends are being set for some reason and you want to get rid of them, call

disable-legend-matplotlibNo legends

Change number of columns in legend

If you have many lines or plots in the same axes, it can get a litle bit difficult to view them all.

Change parameter if you need to:

legend-with-a-single-columnBy default, the legend has a single column
legend-with-two-columnsLegend looks a bit neater with two
columns instead of one.

Use argument to reposition the legend box.

For example, to set the legend box to the right of the plot area:

matplotlib-position-legend-outside-imagePositioning the legend outside the plot area is
useful when you have many lines
in the same plot.

Reorder labels in legend

If you can afford to plot using pandas, you can just use to achieve the same result

Sometimes the order in which legend labels are displayed is not the most adequate.

For example, in the first graph, the order the labels are shown does not match the order the lines are plotted, so it can make visualization a bit harder, especially when there are many groups of data in the same axes.

To modify legend labels:

  • 1) get current labels via after plotting.

  • 2) sort the handles (images) and labels the way you want.

  • 3) call passing the modified handles and labels.

unodered-labels-in-legendPlot with default legend options
reordered-legend-labelsAfter reordering the labels in the legend,
they now match the order in which the
lines were drawn, making it easier
to know which line is which.

Related content

Legend Function in Matplotlib - Pytplot - Python Tutorials

How to specify legend position in matplotlib in graph coordinates

I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

How to put the legend out of the plot

However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?

Edit: A small example is here:

enter image description here

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?


Similar news:

This did not last long. Shurik began to lower Svetka in the ass, the cock fell out and all the remnants of hot sperm poured onto Svetka's ass and from. Her onto my cock and balls. Svetka with even greater agility began to jump on my dick and I was already ready to lower it, but Seryoga said that he.

4531 4532 4533 4534 4535