- Matplotlib 3.0 Cookbook
- Srinivasa Rao Poladi
- 700字
- 2025-04-04 16:06:37
There's more...
Since there are many such possible grids, we will see one more example with four different plots in a 2 x 2 grid, each one with a different type of graph, histogram, line, scatter, and bar graph. In the last example, we kept adding axes one by one, with the plt.subplot() method. In this example, we will define all axes in the grid at once, and then use indexing to access each of them and plot different graphs:
- Read Wine Quality and Iris datasets from .csv files and compute the mean and standard deviation for each of the attributes:
wine_quality = pd.read_csv('winequality.csv', delimiter=';')
iris = pd.read_csv('iris_dataset.csv', delimiter=',')
iris_mean = iris.mean()
iris_std = iris.std()
- This defines the figure and its layout:
fig, axs = plt.subplots(2, 2, figsize=(8, 8))
- Plot the histogram with the alcohol attribute of the Wine Quality dataset on the first axis:
axs[0, 0].hist(wine_quality['alcohol'])
axs[0, 0].set_title('Histogram')
axs[0, 0].set_xlabel('Alcohol Bins')
axs[0, 0].set_ylabel('Frequency')
- Plot the line graph of sepal_length and sepal_width on the second axis:
axs[0, 1].plot(iris['sepal_length'], iris['sepal_width'])
axs[0, 1].set(title='Line', xlabel='Sepal Length', ylabel='Sepal
Width')
- Plot a scatter plot with the petal_length and the petal_width attributes on the third axis:
axs[1, 0].scatter(iris['petal_length'], iris['petal_width'])
axs[1, 0].set(title='Scatter', xlabel='Petal Length', ylabel='Petal
Width')
- Plot a bar graph on the fourth axis:
axs[1, 1].bar(['sepal_l','sepal_w', 'petal_l', 'petal_w'],
iris_mean, yerr=iris_std)
axs[1, 1].set(title='Bar', xlabel='Category', ylabel='Category
Mean')
- Set the title for the overall figure:
plt.suptitle('Subplots Demo')
- Adjust the space in between the plots:
plt.tight_layout(pad=3, w_pad=1.0, h_pad=1.0)
- Display the plot on the screen:
plt.show()
Here is the explanation of how the code works:
- iris.mean() and iris.std() compute the mean and standard deviation for all four attributes in the Iris dataset. These will be used to plot the bar plot on the fourth axis of this figure.
- fig, axs = plt.subplots(2, 2, figsize=(8, 8)) defines 2 x 2 grid and assigns them to the axis list, which will be accessed with respective indexes while plotting the graph on each of these axes.
- axs[0, 0].hist(wine_quality['alcohol']) plots the histogram plot for the alcohol attribute in the Wine Quality dataset. axes[0,0] represents the first plot on the first row and the first column (Python indexing starts with 0).
- axs[0, 0].set_title('Histogram') sets the title for the first plot.
- axs[0, 0].set_xlabel('Alcohol Bins') sets the label for the x axis and axs[0, 0].set_ylabel('Alcohol Bins') sets the label for the y axis.
- axs[0, 1] represents the second plot, placed in the first row and the second column, and a line plot is drawn on this axis. axs[0, 1].set() sets title, xlabel, and ylabel with one command instead of three separate commands.
- axs[1, 0] represents the third plot, placed in the second row and the first column, and a scatter plot is drawn on this axis.
- Finally, axs[1, 1] represents the fourth plot, placed in the second row and the second column, and a bar plot is drawn on this axes. The yerr attribute represents the standard deviation for the group represented by the bar, and it is shown as a black vertical line on top of each bar. The length of the line is relative to all other lines on the bars; the longer the line, the higher the standard deviation for that group (or bar).
- plt.suptitle('Subplots Demo') sets the title for the figure (a combination of all four plots together).
- plt.tight_layout(pad=3, w_pad=1.0, h_pad=1.0) ensures that the labels on the four plots are not overlapping with one another. The pad parameter controls the space at the top of the figure; the higher the number, the larger the gap between the title of the figure and the headers of the two plots below it. w_pad controls the space between two plots in a row, and h_pad controls the space between two plots in a column.
You should see the output plots as shown in the following figure:
In this index-based axes approach, all the plots will be the same size, so we can't manage different sized plots the way we did in the example at the beginning of this recipe.