How to Create Different Subplot Sizes in Matplotlib?

How to Create Different Subplot Sizes in Matplotlib?

If you want to create subplots with different sizes in a single figure using Matplotlib, the GridSpec functionality is particularly useful. GridSpec allows you to create a grid layout for subplots, where you can specify the relative height and width of individual subplots.

Here's a basic example to create subplots with different sizes using GridSpec:

import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # Create a figure fig = plt.figure(figsize=(10, 6)) # Define a GridSpec with 2 rows and 2 columns gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[2, 1]) # Create subplots with different sizes ax0 = plt.subplot(gs[0]) # Top-left subplot ax1 = plt.subplot(gs[1]) # Top-right subplot, twice as wide as ax0 ax2 = plt.subplot(gs[2]) # Bottom-left subplot, half as tall as ax0 ax3 = plt.subplot(gs[3]) # Bottom-right subplot, twice as wide and half as tall as ax0 # Sample plots for demonstration ax0.plot([0, 1, 2], [0, 1, 2]) ax1.plot([0, 1, 2], [2, 1, 0]) ax2.plot([0, 1, 2], [1, 2, 1]) ax3.plot([0, 1, 2], [0, 2, 0]) plt.tight_layout() plt.show() 

In this example:

  • The width_ratios argument specifies the relative widths of columns. Similarly, height_ratios specifies the relative heights of rows.
  • When creating subplots, indexing into the GridSpec object (gs[0], gs[1], etc.) provides the location for each subplot.
  • The resulting figure consists of 4 subplots, where the right column is twice as wide as the left, and the bottom row is half as tall as the top.

Adjust the width_ratios and height_ratios parameters, as well as the number of rows and columns in the GridSpec, to suit your specific requirements.


More Tags

junit google-sheets-api eval imagemagick-convert xampp-vm git-push minify enzyme webpack-4 node-red

More Programming Guides

Other Guides

More Programming Examples