1

我有一个要解决的快速问题。我有一个脚本可以处理大约 2000 个文件,生成图像并将图像保存为 PDF 或图像格式。但我无法阻止图像出现在屏幕上。我阅读和研究但无法解决我的问题。我认为我在 Matplotlib 中设置的后端有问题。但我不是这方面的专家。我尝试按照网站上的说明使用 matplotlib.use('Agg') ,但没有帮助。所以,如果你能帮助我弄清楚发生了什么问题,我将不胜感激。非常感谢!

系统:Ubuntu 13.04 Matplotlib:1.2.1 Python 2.7.4

以下是导入部分脚本的外观:

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, AutoMinorLocator, ScalarFormatter
from pylab import *

编辑:发布更多代码。这只是其中的一部分。我有一个功能:

def plot_vi(t, s1, s2, s3, charttitle, chartnote, celllocation, filename):

fig = plt.figure(figsize=(16, 12))
ax1 = fig.add_subplot(111)
l1, = ax1.plot(t, s1, 'r-', linewidth=0.7)
l2, = ax1.plot(t, s3, '-', linewidth=0.7, color='#00ff00')
ax1.set_xlabel('Test Time (hours)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('Voltage (Volts)', color='r')
for tl in ax1.get_yticklabels():
    tl.set_color('r')

ax2 = ax1.twinx()
l3, = ax2.plot(t, s2, 'b-', linewidth=0.7)
ax2.set_ylabel('Current (Amps)', color='b')
for tl in ax2.get_yticklabels():
    tl.set_color('b')

minorLocator   = AutoMinorLocator()
ax2.xaxis.set_minor_locator(minorLocator)
majorLocator   = MultipleLocator(1)
minorLocator   = MultipleLocator(0.2)
ax2.yaxis.set_major_locator(majorLocator)
ax2.yaxis.set_minor_locator(minorLocator)
majorLocator   = MultipleLocator(0.1)
minorLocator   = MultipleLocator(0.02)
ax1.yaxis.set_major_locator(majorLocator)
ax1.yaxis.set_minor_locator(minorLocator)
ax1.xaxis.grid(color='gray')
ax1.yaxis.grid(color='gray')
lgd = legend([l1, l3, l2], ['voltage', 'current', 'auxiliary'], bbox_to_anchor=(1.05, 1), loc=2)

title(charttitle, fontsize=16)
figtext(0.01, 0.027, chartnote, color='#707070')
figtext(0.01, 0.01, celllocation, color='#707070')
fig.subplots_adjust(right=0.85) 
plt.savefig(filename, dpi=100)plot_vi(t, s1, s2, s3, ChartTitle, ChartNote, CellLocation, PLOTFILENAME)
    plt.savefig(pp, format='pdf')

然后我运行了那个函数:

 plot_vi(t, s1, s2, s3, ChartTitle, ChartNote, CellLocation, PLOTFILENAME)
 plt.savefig(pp, format='pdf')
4

3 回答 3

1

可能在你的脚本中有一个你说的地方plt.show()。将其替换为,您要另存为的名称plt.savefig('fig-name.pdf')在哪里。fig-name.pdf如果要另存为 .png,只需将扩展名更改为.png等。

这是一些关于将多个图像保存为 pdf 的文档;它也可以帮助你。

于 2013-07-03T13:52:05.867 回答
1

好的,看起来我找到了某种解决方案。我强迫 matplotlib 切换后端:

matplotlib.pyplot.switch_backend('Agg')

之后,我的屏幕上没有成千上万的 GUI 窗口。虽然还没有用 PDF 测试过。

来源:从这里

于 2013-07-03T15:01:08.120 回答
0

Please make sure :-

import matplotlib
matplotlib.use('Agg')

Place before import backend_pdf :-

import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, AutoMinorLocator, ScalarFormatter
from pylab import *
于 2013-07-03T14:11:58.290 回答