{"id":9941,"date":"2020-10-30T05:46:40","date_gmt":"2020-10-30T05:46:40","guid":{"rendered":"https:\/\/www.askpython.com\/?p=9941"},"modified":"2020-10-30T05:47:12","modified_gmt":"2020-10-30T05:47:12","slug":"matplotlib-subplots","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/matplotlib\/matplotlib-subplots","title":{"rendered":"Matplotlib Subplots &#8211; Plot Multiple Graphs Using Matplotlib"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>In this article, we will learn how to create Matplotlib subplots.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In practice we often need more than one plot to visualize the variables, this is when subplots come into the picture. <a href=\"https:\/\/www.askpython.com\/python-modules\/matplotlib\/python-matplotlib\" class=\"rank-math-link\">Matplotlib<\/a> subplot method is a convenience function provided to create more than one plot in a single figure. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Creating a Basic Plot Using Matplotlib<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To create a plot in Matplotlib is a simple task, and can be achieved with a single line of code along with some input parameters. The code below shows how to do simple plotting with a single figure.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#Importing required libraries \nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#Create data\ndata = np.arange(1,5,1)\n\n#Plotting the data:\nplt.plot(data)\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"720\" height=\"432\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/simple-plotting.jpeg\" alt=\"Simple Plotting\" class=\"wp-image-9995\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/simple-plotting.jpeg 720w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/simple-plotting-300x180.jpeg 300w\" sizes=\"auto, (max-width: 720px) 100vw, 720px\" \/><figcaption>Simple Plotting<\/figcaption><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><code>plt.plot()<\/code> displays the line plot of input data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Creating Matplotlib Subplots<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now think of a situation where we need to have multiple plots for explaining our data. For example, we have a dataset having temperature and rainfall rate as variables and we need to visualize the data. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One thing that occurs to mind is to plot both variables in a single plot, but the measurement scale for temperature (Kelvin) is different than that of rainfall rate(mm). <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here we need a separate plot for both in order to have visual interpretation. Matplotlib subplot is what we need to make multiple plots and we&#8217;re going to explore this in detail.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Using the subplots() method<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s have some perspective on using <code>matplotlib.subplots<\/code>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The matplotlib subplots() method requires a number of rows and a number of columns as an input argument to it and it returns a figure object and axes object. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each axis object can be accessed using simple indexing. And after having selected the required axes to plot on, the procedure for plotting will follow its normal course as we did in the above code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Let&#8217;s create 4 subplots arranged like a grid. <\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#Importing required libraries\nimport matplotlib.pyplot as plt\n\n# Creates fig and ax from subplots().\nfig , ax = plt.subplots(nrows = 2, ncols = 2)\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"600\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/4-subplots.jpeg\" alt=\"4 Subplots\" class=\"wp-image-9953\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/4-subplots.jpeg 800w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/4-subplots-300x225.jpeg 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/4-subplots-768x576.jpeg 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/4-subplots-160x120.jpeg 160w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/4-subplots-320x240.jpeg 320w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption><strong>4 Subplots<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">2. Accessing subplots<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Accessing individual axes is very simple. Let&#8217;s do some plotting on first and the last subplot.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\n\n#Loading Dataset\ndata = load_iris()\ndf = data.data\n\nfig , ax = plt.subplots(nrows = 2, ncols = 2, figsize=(8,6))\n\n#Plotting on the 1st axes\nax&#x5B;0]&#x5B;0].scatter(df&#x5B;:,0],df&#x5B;:,1] , color = &#039;black&#039;)\n\n#Plotting on the last axes\nax&#x5B;1]&#x5B;1].scatter(df&#x5B;:,1],df&#x5B;:,2] , color = &#039;red&#039;)\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"600\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Accessing-1st-and-4th-Subplots.jpeg\" alt=\"Accessing 1st And 4th Subplots\" class=\"wp-image-9957\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Accessing-1st-and-4th-Subplots.jpeg 800w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Accessing-1st-and-4th-Subplots-300x225.jpeg 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Accessing-1st-and-4th-Subplots-768x576.jpeg 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Accessing-1st-and-4th-Subplots-160x120.jpeg 160w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Accessing-1st-and-4th-Subplots-320x240.jpeg 320w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption><strong>Accessing 1st And 4th Subplots<\/strong><\/figcaption><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Think of each axes as some objects arranged in an 2D array, accessing each subplot is similar to accessing elements from 2D array. <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>ax[0][0]<\/strong> means we first selected first row (index 0) and the first element from that row (index 0). <\/li><li><strong>ax[1][1] <\/strong>means we first selected the second row (index 1) and the second element from that row (index 1).<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. Matplotlib Subplots with shared axis<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In many applications, we need the axis of subplots to be aligned with each other. The matplotlib subplots() method accepts two more arguments namely <code>sharex<\/code> and <code>sharey<\/code> so that all the subplots axis have similar scale.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#Import required libraries\nimport matplotlib.pyplot as plt\n\n#Plotting\nfig, ax = plt.subplots(2, 3, sharex=True, sharey=True)\nfor i in range(0,2):\n    for j in range(0,3):\n        ax&#x5B;i]&#x5B;j].text(0.5, 0.5, str((i,j)),fontsize=18, ha=&#039;center&#039;)\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"900\" height=\"450\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Subplot-with-shared-axis-1.jpeg\" alt=\"Subplot With Shared Axis 1\" class=\"wp-image-9986\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Subplot-with-shared-axis-1.jpeg 900w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Subplot-with-shared-axis-1-300x150.jpeg 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/Subplot-with-shared-axis-1-768x384.jpeg 768w\" sizes=\"auto, (max-width: 900px) 100vw, 900px\" \/><figcaption>Subplots with Shared Axis <\/figcaption><\/figure><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">4. Using add_subplot() method<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>add_subplot<\/code> is an attribute of Matplotlib <code>figure<\/code> object. It is used whenever we wish to add subplots to our figure one by one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s demonstrate this with the example code.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#Importing libraries\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\n\n#Loading Data to plot\ndata = load_iris()\ndf = data.data\n\n#Create a figure object\nfig = plt.figure(figsize=(8,8))\n\n#Adding one subplot to the figure\nax_1 = fig.add_subplot(2, 2, 1) #selecting 1st out of 4 subplots \nax_1.scatter(df&#x5B;:,0],df&#x5B;:,1] , color = &#039;black&#039;)\n\n#Adding one more subplot\nax_2 = fig.add_subplot(2,2,4)\nax_2.scatter(df&#x5B;:,0],df&#x5B;:,1] , color = &#039;red&#039;)\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"576\" height=\"576\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one.jpeg\" alt=\"Adding Subplots One By One\" class=\"wp-image-9989\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one.jpeg 576w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one-300x300.jpeg 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one-150x150.jpeg 150w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one-120x120.jpeg 120w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one-24x24.jpeg 24w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one-48x48.jpeg 48w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/10\/adding-subplots-one-by-one-96x96.jpeg 96w\" sizes=\"auto, (max-width: 576px) 100vw, 576px\" \/><figcaption>Adding Subplots One By One<\/figcaption><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">In the code above, the <code>add_subplot<\/code> attribute of the figure object requires a number of rows and columns as input argument along with the index of subplot. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But here instead of indexing subplots as 2D arrays, we simply need to pass an integer that resembles the figure number. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>fig.add_subplot(2, 2, 1)<\/code> in the code above will first create a 2\u00d72 grid of subplots and return the 1st subplot axes object on which we can plot our data. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this article we saw how we can visualize data on multiple plots in a single figure, use of <code>subplots<\/code> method and number of ways to create subplots.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Happy Learning!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn how to create Matplotlib subplots. In practice we often need more than one plot to visualize the variables, this is when subplots come into the picture. Matplotlib subplot method is a convenience function provided to create more than one plot in a single figure. Creating a Basic Plot Using [&hellip;]<\/p>\n","protected":false},"author":16,"featured_media":9994,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[95],"tags":[],"class_list":["post-9941","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\/9941","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\/16"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=9941"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/9941\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/9994"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=9941"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=9941"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=9941"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}