1

I have a df with some number of columns, and I'm creating bivariate plots using a loop like so:

for col in df.columns[2:len(df.columns)]:
    sns.factorplot(x='xvar', y=col,  data=df)
    sns.despine(offset=10, trim=True)

    plt.show()
    plt.clf()

plt.close()

Instead of displaying all the plots I'd like to save them with the naming convention [xaxis]_y[axis].png. However, I'm not sure how to pass more than 1 item through plt.savefig() where one of the items will change every time. I've seen a few answers that rely on lists (1, 2), but I'm hoping there's a way to achieve the same results without having to create lists to pass through.

LMGagne
  • 1,636
  • 6
  • 24
  • 47
  • 1
    Not sure what you mean by using lists. Regardless, you need to provide a filename for your plot. I assume your column names are strings, so this could be something as simple as plt.savefig(col + ".png"). What is the problem with this? – tnknepp Mar 04 '20 at 17:12

2 Answers2

3

Since python 3.6 you can use f-strings to format strings dynamically:

for col in df.columns[2:]:
    sns.factorplot(x='xvar', y=col, data=df)
    sns.despine(offset=10, trim=True)
    plt.savefig(f'xvar_{col}.png')
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
2
plt.savefig('var1' + '_' + col' + '.png')

Achieved the desired result

LMGagne
  • 1,636
  • 6
  • 24
  • 47