Populating the matplotlib subtask through a loop and function

I need to draw figure subtitles through loop iterations; each iteration calls a function defined in another module (= another py file) that draws a pair of subheadings. Here is what I tried - and alas, it does not work:

1) Before the loop, create a shape with enough rows and two columns:

import matplotlib.pyplot as plt fig, axarr = plt.subplots(nber_rows,2) 

2) Inside the loop on the iter_nber iteration number, call the function that draws each subheading:

  fig, axarr = module.graph_function(fig,axarr,iter_nber,some_parameters, some_data) 

3) This function is basically like this; each iteration creates a pair of subheadings in one line:

  def graph_function(fig,axarr,iter_nber,some_parameters, some_data): axarr[iter_nber,1].plot(--some plotting 1--) axarr[iter_nber,2].plot(--some plotting 2--) return fig,axarr 

This does not work. I end up with an empty figure at the end of the loop. I tried various combinations above, for example, leaving only axarr in the return argument of the function, but to no avail. Obviously, I do not understand the logic of this figure and its subplots.

Any suggestions that are very much appreciated.

+7
python matplotlib subplot
source share
1 answer

The code you posted looks mostly correct. Apart from indexing, as @hitzg mentioned, nothing you do looks terribly unusual.

However, it makes no sense to return an array of shapes and axes from the plot function. (If you need access to a ax.figure object, you can always get it through ax.figure .) It will not change anything to pass them and return them.

Here is a quick example of how this sounds like you are trying to do. Maybe this helps eliminate some confusion?

 import numpy as np import matplotlib.pyplot as plt def main(): nrows = 3 fig, axes = plt.subplots(nrows, 2) for row in axes: x = np.random.normal(0, 1, 100).cumsum() y = np.random.normal(0, 0.5, 100).cumsum() plot(row, x, y) plt.show() def plot(axrow, x, y): axrow[0].plot(x, color='red') axrow[1].plot(y, color='green') main() 

enter image description here

+10
source share

All Articles