python: matplotlib输出文件名

问题描述 投票:0回答:2
import sys
import matplotlib.pyplot as plt
from numpy import *

filename = sys.argv[1]
num_, bin_, count_, err_ = loadtxt(filename, unpack=True)

plt.step(bin_,count_, where='mid', color='red')
plt.yscale('log')

plt.savefig(filename+'.pdf')
plt.show()

在上面的代码里面,我想把输出的图保存为同名的文件名(==sys.argv[1])。

下面的不工作。

plt.savefig(filename+'.pdf')

谁能给我一个合适的建议?

python matplotlib filenames
2个回答
0
投票

https:/matplotlib.org3.1.1api_as_genmatplotlib.pyplot.savefig.html。:

如果没有设置格式,则根据fname的扩展名(如果有的话)推断输出格式,否则根据rcParams["savefig.format"]='png'推断。如果格式被设置,它决定了输出格式。

还有.format : str 文件格式。

format : str 文件格式,例如'png', 'pdf', 'svg',...。未设置时的行为在fname下有记载。

:)


0
投票

尝试使用str replace 方法。

>>> "Hello World".replace("World", "Anatoli")
'Hello Anatoli'

在你的例子中,:

plt.savefig(filename.replace(".py", ".pdf")

这将使用你的文件名,但会删除掉 .py 并写 .pdf 而不是,这是你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.