How to fit/size subplots with aspect and box_aspect in matplotlib (python)

Viewed 364

I'm trying to fit the sizes of 2x2 subplots so they line up correctly. I want to create the following subplot/axes structure:

  • ax1 has a set aspect ratio in data coordinates (e.g. data is not scaled when aspect=1)
  • ax2 and ax3 have a set (box) aspect ratio in display/figure coordinates (e.g. they appear as squares when box_aspect=1)
  • ax1 and ax3 share the x axis limits and have the same width
  • ax1 and ax2 share the y axis limits and have the same height
  • ax4 fits in the last box so that it has the width of ax2 and the height of ax3

I need this for the following project (it's an animation):

  • Imagine having ax1 as the world space in which a point is moving. (the coordinates should not be warped)
  • The adjacent plots show the x(ax3) and y(ax2) coordinates of the point over time. (I want to be able to set the aspect ratio of these subplots)
  • The last axes/plot is not related to any of the coordinates but should fit in nicely.

I created a minimal example and added descriptive text to the picture:

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = plt.subplot(221, anchor='SE', aspect=1, xlim=(0,1), ylim=(0,2))
ax2 = plt.subplot(222, anchor='SW', box_aspect=1, sharey=ax1, xlim=(0,3))
ax3 = plt.subplot(223, anchor='NE', box_aspect=1, sharex=ax1, ylim=(0,4))
ax4 = plt.subplot(224, anchor='NW', xlim=(0,5), ylim=(0,6))

plt.show()

current subplot structure

Notes:

  • the anchors are set so there is not so much whitespace between the subplots
  • the x and y limits are arbitrarily chosen and should not matter
1 Answers

I encountered a similar issue as I was plotting GeoJson data in matplotlib.
I solved it by creating a one subplot figure setting aspect=1

# import the required libraries
import geopandas as gpd
import matplotlib.pyplot as plt

# Define the file path
fp = r"\Your-file-full-path\file.geojson"

# Read the GeoJSON file similarly as Shapefile
mygeojson = gpd.read_file(fp)


# Create a figure with one subplot
fig = plt.figure()

# Plot the grid with column-to-plot (as you set cmap, scheme, and aspect hyper-params)
mygeojson.plot(aspect=1, column = 'geojson-column-to-plot', cmap = 'gist_rainbow', scheme = 'equalinterval', k=9, linewidth=0, legend=True);

# Add title
plt.title("Your GeoDataFrame object title");

# Remove white space around the figure
plt.tight_layout()
Related