Iteratively generating subplots in matplotlib by row and column - only final axes plotting











up vote
0
down vote

favorite












I am writing code to plot cross correlations of every time-series in my data against all others, with two for-loops to index the row and column position respectively (column loop nested within the row loop).



Currently only the final axes (i.e. bottom right corner) of the figure is displaying any data, and each iteration of the loop appears to be plotting on this axes. I am wondering if I have made any obvious mistakes with the order of commands in the nested for loops, or if I am misinterpreting the input arguments to matplotlib functions like subplots....



The code is as below:



fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)

for n in range(data_num): #row index
for p in range(data_num): # column index
x = data_df.iloc[:,n] #get data for ROI according to row index
print(x.head())
x = x.values
y = data_df.iloc[:,p] #get data for ROI according to column index
print(y.head())
y = y.values
axes[n,p] = plt.xcorr(x,y,normed=True) #axes [row,column] = cross correlation plot of above data
print(f'plotting at index [ {n} , {p}]')









share|improve this question


























    up vote
    0
    down vote

    favorite












    I am writing code to plot cross correlations of every time-series in my data against all others, with two for-loops to index the row and column position respectively (column loop nested within the row loop).



    Currently only the final axes (i.e. bottom right corner) of the figure is displaying any data, and each iteration of the loop appears to be plotting on this axes. I am wondering if I have made any obvious mistakes with the order of commands in the nested for loops, or if I am misinterpreting the input arguments to matplotlib functions like subplots....



    The code is as below:



    fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)

    for n in range(data_num): #row index
    for p in range(data_num): # column index
    x = data_df.iloc[:,n] #get data for ROI according to row index
    print(x.head())
    x = x.values
    y = data_df.iloc[:,p] #get data for ROI according to column index
    print(y.head())
    y = y.values
    axes[n,p] = plt.xcorr(x,y,normed=True) #axes [row,column] = cross correlation plot of above data
    print(f'plotting at index [ {n} , {p}]')









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am writing code to plot cross correlations of every time-series in my data against all others, with two for-loops to index the row and column position respectively (column loop nested within the row loop).



      Currently only the final axes (i.e. bottom right corner) of the figure is displaying any data, and each iteration of the loop appears to be plotting on this axes. I am wondering if I have made any obvious mistakes with the order of commands in the nested for loops, or if I am misinterpreting the input arguments to matplotlib functions like subplots....



      The code is as below:



      fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)

      for n in range(data_num): #row index
      for p in range(data_num): # column index
      x = data_df.iloc[:,n] #get data for ROI according to row index
      print(x.head())
      x = x.values
      y = data_df.iloc[:,p] #get data for ROI according to column index
      print(y.head())
      y = y.values
      axes[n,p] = plt.xcorr(x,y,normed=True) #axes [row,column] = cross correlation plot of above data
      print(f'plotting at index [ {n} , {p}]')









      share|improve this question













      I am writing code to plot cross correlations of every time-series in my data against all others, with two for-loops to index the row and column position respectively (column loop nested within the row loop).



      Currently only the final axes (i.e. bottom right corner) of the figure is displaying any data, and each iteration of the loop appears to be plotting on this axes. I am wondering if I have made any obvious mistakes with the order of commands in the nested for loops, or if I am misinterpreting the input arguments to matplotlib functions like subplots....



      The code is as below:



      fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)

      for n in range(data_num): #row index
      for p in range(data_num): # column index
      x = data_df.iloc[:,n] #get data for ROI according to row index
      print(x.head())
      x = x.values
      y = data_df.iloc[:,p] #get data for ROI according to column index
      print(y.head())
      y = y.values
      axes[n,p] = plt.xcorr(x,y,normed=True) #axes [row,column] = cross correlation plot of above data
      print(f'plotting at index [ {n} , {p}]')






      python python-3.x matplotlib






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 at 12:38









      OsDavy

      83




      83
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          It's a, perhaps unfortunate, way that pyplot and matplotlib works: you have to create the plots on the respective axes, not assign the result from a pyplot.xcorr call to an axes. Thus: axis[n,p].xcorr(...). So the interface is suddenly somewhat more object-oriented than the usual direct pyplot calls.



          All the plots ends up in just the last figure, because you are calling



          plt.xcorr(x,y,normed=True)


          It doesn't matter if you then assign the return value to the axes array elements, which you shouldn't, as that destroys the original axes array.
          plt.xcorr will then plot all the data in the same plot on top of each other, because pyplot generally acts on the currently active axes, which is the last one created via plt.subplots().





          That's for an explanation. Here's an example solution (with random data and a simple scatter plot):



          import numpy as np
          import matplotlib.pyplot as plt

          data_num = 3

          x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
          y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

          fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
          for n in range(data_num): #row index
          for p in range(data_num): # column index
          # Call `scatter` or any plot function on the
          # respective `axes` object itself
          axes[n,p].scatter(x[n,p], y[n,p])
          print(f'plotting at index [ {n} , {p}]')
          plt.savefig('figure.png')


          and figure.png looks like (sorry, no colour or symbol variation, just bare bones scatter plots):



          enter image description here






          share|improve this answer























          • Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
            – OsDavy
            Nov 20 at 13:08










          • I corrected the part about the explanation.
            – ImportanceOfBeingErnest
            Nov 20 at 13:56











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393172%2fiteratively-generating-subplots-in-matplotlib-by-row-and-column-only-final-axe%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          It's a, perhaps unfortunate, way that pyplot and matplotlib works: you have to create the plots on the respective axes, not assign the result from a pyplot.xcorr call to an axes. Thus: axis[n,p].xcorr(...). So the interface is suddenly somewhat more object-oriented than the usual direct pyplot calls.



          All the plots ends up in just the last figure, because you are calling



          plt.xcorr(x,y,normed=True)


          It doesn't matter if you then assign the return value to the axes array elements, which you shouldn't, as that destroys the original axes array.
          plt.xcorr will then plot all the data in the same plot on top of each other, because pyplot generally acts on the currently active axes, which is the last one created via plt.subplots().





          That's for an explanation. Here's an example solution (with random data and a simple scatter plot):



          import numpy as np
          import matplotlib.pyplot as plt

          data_num = 3

          x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
          y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

          fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
          for n in range(data_num): #row index
          for p in range(data_num): # column index
          # Call `scatter` or any plot function on the
          # respective `axes` object itself
          axes[n,p].scatter(x[n,p], y[n,p])
          print(f'plotting at index [ {n} , {p}]')
          plt.savefig('figure.png')


          and figure.png looks like (sorry, no colour or symbol variation, just bare bones scatter plots):



          enter image description here






          share|improve this answer























          • Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
            – OsDavy
            Nov 20 at 13:08










          • I corrected the part about the explanation.
            – ImportanceOfBeingErnest
            Nov 20 at 13:56















          up vote
          0
          down vote



          accepted










          It's a, perhaps unfortunate, way that pyplot and matplotlib works: you have to create the plots on the respective axes, not assign the result from a pyplot.xcorr call to an axes. Thus: axis[n,p].xcorr(...). So the interface is suddenly somewhat more object-oriented than the usual direct pyplot calls.



          All the plots ends up in just the last figure, because you are calling



          plt.xcorr(x,y,normed=True)


          It doesn't matter if you then assign the return value to the axes array elements, which you shouldn't, as that destroys the original axes array.
          plt.xcorr will then plot all the data in the same plot on top of each other, because pyplot generally acts on the currently active axes, which is the last one created via plt.subplots().





          That's for an explanation. Here's an example solution (with random data and a simple scatter plot):



          import numpy as np
          import matplotlib.pyplot as plt

          data_num = 3

          x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
          y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

          fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
          for n in range(data_num): #row index
          for p in range(data_num): # column index
          # Call `scatter` or any plot function on the
          # respective `axes` object itself
          axes[n,p].scatter(x[n,p], y[n,p])
          print(f'plotting at index [ {n} , {p}]')
          plt.savefig('figure.png')


          and figure.png looks like (sorry, no colour or symbol variation, just bare bones scatter plots):



          enter image description here






          share|improve this answer























          • Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
            – OsDavy
            Nov 20 at 13:08










          • I corrected the part about the explanation.
            – ImportanceOfBeingErnest
            Nov 20 at 13:56













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          It's a, perhaps unfortunate, way that pyplot and matplotlib works: you have to create the plots on the respective axes, not assign the result from a pyplot.xcorr call to an axes. Thus: axis[n,p].xcorr(...). So the interface is suddenly somewhat more object-oriented than the usual direct pyplot calls.



          All the plots ends up in just the last figure, because you are calling



          plt.xcorr(x,y,normed=True)


          It doesn't matter if you then assign the return value to the axes array elements, which you shouldn't, as that destroys the original axes array.
          plt.xcorr will then plot all the data in the same plot on top of each other, because pyplot generally acts on the currently active axes, which is the last one created via plt.subplots().





          That's for an explanation. Here's an example solution (with random data and a simple scatter plot):



          import numpy as np
          import matplotlib.pyplot as plt

          data_num = 3

          x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
          y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

          fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
          for n in range(data_num): #row index
          for p in range(data_num): # column index
          # Call `scatter` or any plot function on the
          # respective `axes` object itself
          axes[n,p].scatter(x[n,p], y[n,p])
          print(f'plotting at index [ {n} , {p}]')
          plt.savefig('figure.png')


          and figure.png looks like (sorry, no colour or symbol variation, just bare bones scatter plots):



          enter image description here






          share|improve this answer














          It's a, perhaps unfortunate, way that pyplot and matplotlib works: you have to create the plots on the respective axes, not assign the result from a pyplot.xcorr call to an axes. Thus: axis[n,p].xcorr(...). So the interface is suddenly somewhat more object-oriented than the usual direct pyplot calls.



          All the plots ends up in just the last figure, because you are calling



          plt.xcorr(x,y,normed=True)


          It doesn't matter if you then assign the return value to the axes array elements, which you shouldn't, as that destroys the original axes array.
          plt.xcorr will then plot all the data in the same plot on top of each other, because pyplot generally acts on the currently active axes, which is the last one created via plt.subplots().





          That's for an explanation. Here's an example solution (with random data and a simple scatter plot):



          import numpy as np
          import matplotlib.pyplot as plt

          data_num = 3

          x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
          y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

          fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
          for n in range(data_num): #row index
          for p in range(data_num): # column index
          # Call `scatter` or any plot function on the
          # respective `axes` object itself
          axes[n,p].scatter(x[n,p], y[n,p])
          print(f'plotting at index [ {n} , {p}]')
          plt.savefig('figure.png')


          and figure.png looks like (sorry, no colour or symbol variation, just bare bones scatter plots):



          enter image description here







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 at 13:56









          ImportanceOfBeingErnest

          123k10127203




          123k10127203










          answered Nov 20 at 13:03









          9769953

          1,344311




          1,344311












          • Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
            – OsDavy
            Nov 20 at 13:08










          • I corrected the part about the explanation.
            – ImportanceOfBeingErnest
            Nov 20 at 13:56


















          • Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
            – OsDavy
            Nov 20 at 13:08










          • I corrected the part about the explanation.
            – ImportanceOfBeingErnest
            Nov 20 at 13:56
















          Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
          – OsDavy
          Nov 20 at 13:08




          Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......' to 'axes[n,p].xcorr(....' Really helpful, thank you!
          – OsDavy
          Nov 20 at 13:08












          I corrected the part about the explanation.
          – ImportanceOfBeingErnest
          Nov 20 at 13:56




          I corrected the part about the explanation.
          – ImportanceOfBeingErnest
          Nov 20 at 13:56


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393172%2fiteratively-generating-subplots-in-matplotlib-by-row-and-column-only-final-axe%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'