1

I'm having trouble getting something like this to work:

def make_plots(data, ax):
    sns.lineplot(data,..., ax=ax)
    sns.scatterplot(data, ...., ax=ax)
    return ???

fig, ax = plt.subplots()
for i in range(5):
    make_plot(data[i], ax)
plt.savefig("all5runs.png")

So I have a function that plots a lineplot and scatterplot, hopefully on the same axis. I'd like to keep all 5 runs through the data plotted on one figure, and then save the figure. I'm note sure what make_plots() should return, or if I'm passing around the figure data correctly. How can I make this work?

Edit: Currently, I'm just getting a blank canvas in all5runs.png

theQman
  • 1,690
  • 6
  • 29
  • 52
  • *I'm not sure what `make_plots()` should return* Well, what do you need? Is your current approach not working? If it's not working, what's happening? – Paul H Jun 12 '19 at 00:04
  • https://stackoverflow.com/help/minimal-reproducible-example – Paul H Jun 12 '19 at 00:18

1 Answers1

1

IIUC, you need something like this: Since ax is defined with a global scope, and is passed to the function as an argument, the changes will be updated during each for loop call

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

def make_plots(x, y, ax):
    sns.lineplot(x, y, ax=ax)
    sns.scatterplot(x, y, ax=ax)
    return 

fig, ax = plt.subplots()

for i in range(5):
    x = np.arange(5)
    make_plots(x, x*(i+1), ax)
# plt.show() # Uncomment for showing the figure
plt.savefig('all5runs.png')    

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • How do you actually display/save the figure at the end? – theQman Jun 12 '19 at 00:13
  • @theQman : Check my edit. Try it out and let me know if it works – Sheldore Jun 12 '19 at 00:16
  • Thank you. I'm curious about your comment about 'ax' being global. If I had an 'ax1' and 'ax2' being worked on simultaneously, how would I go about saveing/displaying the relevant ones? – theQman Jun 12 '19 at 00:53
  • @theQman : Please explain the ax1, ax2 thing in your question what you mean by that – Sheldore Jun 12 '19 at 01:09
  • @theQman : For the comment on global scope, read [this](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Sheldore Jun 12 '19 at 01:20