简体   繁体   English

使用 Matplotlib savefig 动态命名

[英]Dynamic naming using Matplotlib savefig

I have a df with some number of columns, and I'm creating bivariate plots using a loop like so:我有一个带有一些列的 df,我正在使用这样的循环创建二元图:

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.我不想显示所有绘图,而是使用命名约定 [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.但是,我不确定如何通过 plt.savefig() 传递 1 个以上的项目,其中一个项目每次都会更改。 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.我已经看到了一些依赖于列表 ( 1 , 2 ) 的答案,但我希望有一种方法可以实现相同的结果,而无需创建要通过的列表。

plt.savefig('var1' + '_' + col' + '.png')

达到了想要的结果

Since python 3.6 you can use f-strings to format strings dynamically:python 3.6您可以使用f-strings strings 动态格式化字符串:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM