{"id":49430,"date":"2023-04-26T07:51:32","date_gmt":"2023-04-26T07:51:32","guid":{"rendered":"https:\/\/www.askpython.com\/?p=49430"},"modified":"2023-04-26T07:51:34","modified_gmt":"2023-04-26T07:51:34","slug":"place-legend-outside-plot-matplotlib","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/matplotlib\/place-legend-outside-plot-matplotlib","title":{"rendered":"How to Place the Legend Outside the Plot Using Matplotlib?"},"content":{"rendered":"\n<p>Legend in terms of a graph or any plot provides the description of the elements inside the plot. These elements can be the entities plotted on the graph, their scales, their colors, and so on. A legend is usually a box placed at the top right or left corner of the graph, but its location can be customized.<\/p>\n\n\n\n<p>The matplotlib library is a powerful, open-source tool for data visualization. This library includes a number of plots including 3D plots for visualizing the data which helps us to understand and analyze the data in a better way. We can even visualize a data frame or a series of the Pandas library with Matplotlib.<\/p>\n\n\n\n<p>The matplotlib has many functions to work with data visualization. It has a function called <code>legend()<\/code> that specifically assigns a legend to the plot of your data.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.askpython.com\/python-modules\/matplotlib\/python-matplotlib\">Visit this article to know more about the types of plots available in Matplotlib.<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Prerequisites<\/strong><\/h2>\n\n\n\n<p>Before we move on to using the Matplotlib library, we need to first ensure that it is installed in our systems. You can install the library using the <code>pip<\/code> command as shown below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; highlight: [1,3,5]; title: ; notranslate\" title=\"\">\nUsing the terminal\npip install matplotlib\nInstalling in any notebook such as Colab or Jupyter\n! pip install matplotlib\nUsing the conda command prompt\nconda install -c conda-forge matplotlib\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\"><strong>What Is a Legend?<\/strong><\/h2>\n\n\n\n<p>A legend is a small box that describes or gives meaning to the plot of your data. It is usually placed in the top right or left corner of the plot, but we can customize the location and the appearance of the legend using the <code>legend<\/code> function.<\/p>\n\n\n\n<p>Let us see one example of this method using the syntax given below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nmatplotlib.pyplot.legend(*args, **kwargs)\n<\/pre><\/div>\n\n\n<p>The important parameters of this function are listed and explained below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport matplotlib.pyplot as plt\nx=&#x5B;2,4,6,8,10]\ny=&#x5B;1,3,5,7,11]\nz=&#x5B;2,3,5,7,11]\nplt.plot(x, y, label=&#039;Even&amp;Odd&#039;)\nplt.plot(x, z, label=&#039;Even&amp;Prime&#039;)\nplt.plot(y,z,label=&#039;Odd&amp;Prime&#039;)\nplt.legend(title=&#039;LEGEND&#039;)\nplt.title(&#039;Even,Odd&amp;Prime Numbers&#039;)\nplt.show()\n<\/pre><\/div>\n\n\n<p>Once you have installed the matplotlib library in your environment. You can import it using the first line of the code.<\/p>\n\n\n\n<p>We are creating three lists that contain even numbers, odd numbers, and prime numbers. They are named x,y, and z respectively.<\/p>\n\n\n\n<p>Next, we are calling the <code>plot<\/code> function three times to plot the combination of even-odd numbers( x and y), even-prime numbers(x and z), and odd-prime numbers(y and z) one after the other. These plots are also named using the <code>label<\/code> property. <\/p>\n\n\n\n<p>The <code>legend<\/code> function is called which displays the color of the plot and the label associated with it. We are also specifying the title of the legend.<\/p>\n\n\n\n<p>The <code>title<\/code> is used to give a name to the entire plot or graph.<\/p>\n\n\n\n<p>The <code>show<\/code> function is used to display the graph.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"859\" height=\"685\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-with-title.png\" alt=\"Legend With Title\" class=\"wp-image-49507\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-with-title.png 859w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-with-title-300x239.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-with-title-768x612.png 768w\" sizes=\"auto, (max-width: 859px) 100vw, 859px\" \/><figcaption class=\"wp-element-caption\">Legend With Title<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Place the Legend Outside the Plot?<\/strong><\/h2>\n\n\n\n<p>In the previous example we have seen how by default, the legend appears inside the plot or graph boundaries. But there is a way to place the legend outside the plot using some techniques.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.askpython.com\/python-modules\/pandas\/data-frame-index-for-x-axis\" data-type=\"post\" data-id=\"49292\">Related: Visit this article to know how to use the index of a data frame as the label for X-axis.<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Using the Bbox to Anchor<\/strong><\/h3>\n\n\n\n<p>This property is an attribute of the legend function used to place the box in correspondence to its location.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport matplotlib.pyplot as plt\nx = &#x5B;1, 2, 3, 4, 5]\ny = &#x5B;2, 4, 6, 8, 10]\nz = &#x5B;1, 3, 5, 7, 9]\nplt.plot(x, y, label=&#039;Line 1&#039;)\nplt.plot(y, z, label=&#039;Line 2&#039;)\nplt.legend( bbox_to_anchor=(1.1,1.05),shadow=True,title=&#039;Legend&#039;)\nplt.title(&#039;Example&#039;)\nplt.xlabel(&#039;X-axis&#039;)\nplt.ylabel(&#039;Y-axis&#039;)\nplt.show()\n<\/pre><\/div>\n\n\n<p>We are importing the matplotlib library as plt in the first line.<\/p>\n\n\n\n<p>Next, we are creating three lists named x,y, and z that contain random elements.<\/p>\n\n\n\n<p>Next, we are plotting two lines &#8211; x with respect to y and y with respect to z. These lines are given labels with the help of <code>label<\/code>.<\/p>\n\n\n\n<p>The legend function is used to create a legend that takes the argument <code>bbox_to_anchor<\/code> which has some coordinates to place the legend. The shadow property is used to create a shadow effect for the box. We can also provide the title to the legend using <code>title<\/code>.<\/p>\n\n\n\n<p>The next three lines are used to provide the title of the graph and names for the X and Y axes.<\/p>\n\n\n\n<p>The <code>show<\/code> method is used to display the plot.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"666\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Using-bbox-to-place-the-legend-outside-the-plot-1024x666.png\" alt=\"Using Bbox To Place The Legend Outside The Plot\" class=\"wp-image-49550\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Using-bbox-to-place-the-legend-outside-the-plot-1024x666.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Using-bbox-to-place-the-legend-outside-the-plot-300x195.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Using-bbox-to-place-the-legend-outside-the-plot-768x500.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Using-bbox-to-place-the-legend-outside-the-plot.png 1122w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Using Bbox To Place The Legend Outside The Plot<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Placing the Legend on the Border<\/strong><\/h3>\n\n\n\n<p>We can place the legend where we want if we can know the correct coordinates to use to get the desired output.<\/p>\n\n\n\n<p>Let us see how we can put a legend on the border of the graph.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport matplotlib.pyplot as plt\nx = &#x5B;1, 2, 3, 4, 5]\ny= &#x5B;2, 4, 6, 8, 10]\nz = &#x5B;1,11,3,4,7]\nplt.plot(x, y, label=&#039;Line 1&#039;)\nplt.plot(x, z, label=&#039;Line 2&#039;)\nplt.legend(bbox_to_anchor=(0.9,0.8),title=&#039;Legend&#039;,shadow=True)\nplt.title(&#039;Example&#039;)\nplt.xlabel(&#039;X-axis&#039;)\nplt.ylabel(&#039;Y-axis&#039;)\nplt.show()\n<\/pre><\/div>\n\n\n<p>The first step is to import the matplotlib library. <\/p>\n\n\n\n<p>The next three lines create three different lists named x,y, and z that have some numbers.<\/p>\n\n\n\n<p>We are plotting two lines- x with respect to y and x with respect to z. These lines are plotted using the <code>plot<\/code> function.<\/p>\n\n\n\n<p>Next, we are creating a legend for this graph using the <code>bbox_to_anchor<\/code> property. The coordinates we chose are (0.9,0.8) which results in the legend on the right side border in the center. The shadow property is used to create a shadow effect for the box.<\/p>\n\n\n\n<p>The next three lines create a title for the graph and also name the x and y axes.<\/p>\n\n\n\n<p>The show method is used to display the graph as output.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"973\" height=\"725\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-on-the-border.png\" alt=\"Legend On The Border\" class=\"wp-image-49552\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-on-the-border.png 973w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-on-the-border-300x224.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-on-the-border-768x572.png 768w\" sizes=\"auto, (max-width: 973px) 100vw, 973px\" \/><figcaption class=\"wp-element-caption\">Legend On The Border<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Using the Loc Property With Bbox<\/strong><\/h3>\n\n\n\n<p>In this example, we are going to use the <code>loc<\/code> attribute along with the <code>bbox_to_anchor<\/code> to create a unique legend on top of the graph.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport pandas as pd\nimport matplotlib.pyplot as plt\ngroc = {&#039;Food&#039;: &#x5B;&#039;Tacos&#039;, &#039;Mac and Cheese&#039;, &#039;Carbonara&#039;, &#039;Lasagna&#039;, &#039;Croissant&#039;],\n        &#039;Calories&#039;: &#x5B;226, 164, 574, 135, 406],\n        &#039;Quantity&#039;:&#x5B;3,1,2,3,1]}\ndf = pd.DataFrame(groc)\nplt.plot(df&#x5B;&#039;Food&#039;], df&#x5B;&#039;Calories&#039;], label=&#039;F&amp;C&#039;)\nplt.plot(df&#x5B;&#039;Food&#039;], df&#x5B;&#039;Quantity&#039;], label=&#039;F&amp;Q&#039;)\nplt.title(&#039;Different foods and their calories&#039;)\nplt.xlabel(&#039;Food Item&#039;)\nplt.ylabel(&#039;Calories&#039;)\nplt.legend(loc=&#039;center right&#039;, bbox_to_anchor=(0.3,1.1),ncol=2,fancybox=True)\nplt.show()\n<\/pre><\/div>\n\n\n<p>We are going to plot a data frame and for that, we need to first import the Pandas library. We are also importing the matplotlib library in the next line.<\/p>\n\n\n\n<p>A dictionary called groc is created that contains a few food items, their respective calories, and the quantity purchased. This dictionary is converted to a data frame with the help of the method <code>pd.DataFrame<\/code>. <\/p>\n\n\n\n<p>We are plotting the Food column with respect to Calories in the first plot and Food with respect to Quantity in the second plot. Their respective labels are given.<\/p>\n\n\n\n<p>Next, we are specifying the title and the labels for the x and y axes. The legend function is used to create a box that contains the description of the graph, We are using the <code>loc<\/code> property which is given to be <code>center right<\/code> and the <code>bbox<\/code> coordinates used are (0.3,1.1). The <code>ncol<\/code> parameter is used to define how many columns the legend box should have. In this case, it is 2. The <code>fancybox<\/code> is used to create rounded edges for the box. <\/p>\n\n\n\n<p>Finally, the show method is used to display the graph.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"917\" height=\"767\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-using-bbox-and-loc.png\" alt=\"Legend Using Bbox And Loc\" class=\"wp-image-49553\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-using-bbox-and-loc.png 917w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-using-bbox-and-loc-300x251.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/04\/Legend-using-bbox-and-loc-768x642.png 768w\" sizes=\"auto, (max-width: 917px) 100vw, 917px\" \/><figcaption class=\"wp-element-caption\">Legend Using Bbox And Loc<\/figcaption><\/figure>\n\n\n\n<p>To conclude, we have seen what is the legend of a graph in matplotlib. It is a box that describes the elements of the graph such as the type of plot, the elements being plotted, and so on. By default, this legend appears inside the plot boundary when using the legend function of the matplotlib.<\/p>\n\n\n\n<p>The matplotlib is a data visualization tool consisting of a number of plots to help us visualize data in a better way.<br>We have seen the example of a simple legend by plotting three plots: Even-Odd numbers, Even-Prime numbers, and Odd-Prime numbers.<br>We created a legend for this plot including the title for it.<\/p>\n\n\n\n<p>Coming to placing the legend outside the plot, we have seen three approaches to it.<br>In the first method, we used the bbox property of the legend function to define a pair of coordinates that place the legend outside the graph boundary with a shadow effect and title.<\/p>\n\n\n\n<p>In the next method, we used the same bbox_to_anchor property and different coordinates that place the legend on the right side border just above the center.<\/p>\n\n\n\n<p>In the last example, we used the loc parameter of the legend function along with the bbox property. We plotted a data frame of three different columns inside it. The <code>ncol<\/code> parameter is used to define the number of columns to appear in the legend. We also gave a rounded edge to the box with the help of <code>fancybox<\/code>.<\/p>\n\n\n\n<p>These results can be customized and fun to experiment with. Have fun experimenting with the above examples!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>References<\/strong><\/h2>\n\n\n\n<p><a href=\"https:\/\/matplotlib.org\/stable\/api\/_as_gen\/matplotlib.pyplot.legend.html\" target=\"_blank\" rel=\"noopener\">You can find more about the legend function here.<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/stackoverflow.com\/questions\/4700614\/how-to-put-the-legend-outside-the-plot\" target=\"_blank\" rel=\"noopener\">Refer to this StackOverflow answer chain<\/a> for more examples of placing legends outside the plot using matplotlib.<\/p>\n\n\n\n<p>lib<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Legend in terms of a graph or any plot provides the description of the elements inside the plot. These elements can be the entities plotted on the graph, their scales, their colors, and so on. A legend is usually a box placed at the top right or left corner of the graph, but its location [&hellip;]<\/p>\n","protected":false},"author":55,"featured_media":49514,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[95],"tags":[],"class_list":["post-49430","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-matplotlib"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/49430","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/55"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=49430"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/49430\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/49514"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=49430"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=49430"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=49430"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}