In the previous segments, you learnt about the basic ways to make plots.
Sometimes, it is beneficial to counterpose different plots next to each other. For example, say you have some data on e-commerce purchases. If you want to analyse the number of purchases across different categories, then you can make multiple bar charts for each category: for instance, one for male buyers and one for female buyers. These two charts, placed next to each other, make it easy to compare the buying patterns of the male and female consumers.
Different plots presented in a single plot object are commonly referred to as subplots. Let's learn how to create subplots inside a single plot in Matplotlib. You can refer to the notebook provided below for this segment.
To recap, you can use the following Matplotlib command to create subplots in Python:
fig, ax = plt.subplots()
: It initiates a figure which will be used to comprises of multiple graphs in a single chart.Subplots are a good way to show multiple plots together for comparison. In the above video, you learnt how to plot different categories together in the same chart. However, subplots offer the ability to create an array of plots, and you can have multiple charts next to each other like the elements of an array.
Let’s try to understand this with the example in the following video.
# The legend for the last subplot is incorrectly displayed. In a subplot, you have to specify legend for each subplot using the following command:
plt.legend([subplot_1, subplot_2, subplot_3],["label 1", "label 2", "label 3"]) # list of subplots along with the list of the names to appear in the legend table # For the above case: plt.legend([africa, aspac, europe], ["Africa", "Asia Pacific", "Europe"])
You can use the following command to create an array of plots.
plt.subplot(nrow, ncol, x)
: It creates a subplot. 'nrow' and 'ncol' are the dimensions of the array inside the figure, and 'x' is the position in the array.