Skip to content

Instantly share code, notes, and snippets.

@jabarragann
Created November 8, 2023 01:17
Show Gist options
  • Save jabarragann/aac476e0ac757b7f34064c060f20ffc2 to your computer and use it in GitHub Desktop.
Save jabarragann/aac476e0ac757b7f34064c060f20ffc2 to your computer and use it in GitHub Desktop.
Obtaining subplot_params of matplotlib figure

Obtaining subplot_params of matplotlib figure

This script shows how to print the subplot_params of a matplotlib figure. The usecase for this script is to be able to visualize any parameter that was manually change, such that the next time you open your plot it will look the same.

  1. Create plot
  2. Modify size and subplot parameters.
  3. create the plot again with the printed parameters.

Notes

Tested on python 3.10 and matplotlib 3.8.0

from matplotlib import pyplot as plt
import numpy as np
# Step three: paste the obtained parameters from step one here.
sub_params = dict(top=0.92, bottom=0.11, left=0.12, right=0.90, hspace=0.50, wspace=0.20, )
figsize = (5.95, 4.89)
fig, axes = plt.subplots(3,1, figsize=figsize)
fig.subplots_adjust(**sub_params)
# Step one create a plot.
# fig, axes = plt.subplots(3,1)
for i in range(3):
data = np.sin(np.arange(0, 300)* np.pi*2/300*(i+1)*2)
axes[i].plot(data)
axes[i].set_title(f"Joint {i+1}")
plt.show()
# Get last subplot params
sub_params = fig.subplotpars
dict_str = "sub_params = dict("
for param in ["top", "bottom", "left", "right", "hspace", "wspace"]:
dict_str = dict_str + f"{param}={getattr(sub_params, param):0.2f}, "
dict_str = dict_str + ")"
# Get figure size
fig_size = fig.get_size_inches()
fig_str = f"figsize = ({fig_size[0]:0.2f}, {fig_size[1]:0.2f})"
print(dict_str)
print(fig_str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment