Subtitle Return Values

I'm currently trying to get to know the matplotlib.pyplot library. After seeing some examples and tutorials, I noticed that the subplots function also has some return values, which are usually used later. However, on the matplotlib website, I could not find any specification about what exactly is being returned, and none of the examples are the same (although this is usually an ax object). Can you guys give me some pointers on what is coming back and how I can use it. Thanks in advance!

+10
matplotlib
source share
2 answers

The documentation says that matplotlib.pyplot.subplots returns an instance of Figure and an array (or one) of Axes (an array or not depending on the number of subheadings).

General use:

 import matplotlib.pyplot as plt import numpy as np f, axes = plt.subplots(1,2) # 1 row containing 2 subplots. # Plot random points on one subplots. axes[0].scatter(np.random.randn(10), np.random.randn(10)) # Plot histogram on the other one. axes[1].hist(np.random.randn(100)) # Adjust the size and layout through the Figure-object. f.set_size_inches(10, 5) f.tight_layout() 
+13
source share

Typically, matplotlib.pyplot.subplots () returns an instance of a shape and an object or an array of Axes objects.

Since you have not published the code that you are trying to get your hands dirty, I will do this by following 2 test cases:

case 1: when the number of required plots (dimension) is mentioned

 import matplotlib.pyplot as plt #importing pyplot of matplotlib import numpy as np x = [1, 3, 5, 7] y = [2, 4, 6, 8] fig, axes = plt.subplots(2, 1) axes[0].scatter(x, y) axes[1].boxplot(x, y) plt.tight_layout() plt.show() 

enter image description here

As you can see here, since we gave the required number of subplots, (2.1) in this case means "no." rows, r = 2 and no. columns, c = 1. In this case, the subplot returns an instance of the figure along with an array of axes whose length is equal to the total number no. from sections = r * c, in this case = 2.

case 2: when the number of subplots (dimension) is not mentioned

 import matplotlib.pyplot as plt #importing pyplot of matplotlib import numpy as np x = [1, 3, 5, 7] y = [2, 4, 6, 8] fig, axes = plt.subplots() #size has not been mentioned and hence only one subplot #is returned by the subplots() method, along with an instance of a figure axes.scatter(x, y) #axes.boxplot(x, y) plt.tight_layout() plt.show() 

enter image description here

In this case, neither size nor size was explicitly mentioned, therefore only one auxiliary section is created, except for the copy of the figure.

You can also control the size of ancillary sites using the squeeze keyword. See the documentation . This is an optional argument with a default value of True.

+1
source share

All Articles