Skip to content

Instantly share code, notes, and snippets.

@ghl3
Created May 18, 2013 17:01
Show Gist options
  • Select an option

  • Save ghl3/5605126 to your computer and use it in GitHub Desktop.

Select an option

Save ghl3/5605126 to your computer and use it in GitHub Desktop.
Get next matplotlib subplot
def get_next_subplot():
"""
Create and move to the next subplot
in a grid of matplotlib subplots
"""
# Get the current plot
ax = plt.gca()
# Check if the current plot is a subplot
if ax.__class__.__name__ != "AxesSubplot":
print "Cannot get next subplot, current axis is not a subplot"
raise Exception()
if ax.is_last_col() and ax.is_last_row():
print "Cannot get next subplot, on last row and column"
raise Exception()
# Do some magic to get the current subplot index
row, col = ax.rowNum, ax.colNum
ax.numRows, ax.numCols
idx = ax.numCols*row + col + 1
next_idx = idx + 1
print "Creating Subplot: (%s, %s, %s)" % (ax.numRows, ax.numCols, next_idx)
plt.subplot(ax.numRows, ax.numCols, next_idx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment