Python 使用 matplotlib 将绘图保存为 pdf 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21364405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving plots to pdf files using matplotlib
提问by aloha
I want to save more than 1 plot to a pdf file. Here is my code:
我想将 1 个以上的图保存到 pdf 文件中。这是我的代码:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
def function_plot(X,Y):
plt.figure()
plt.clf()
pp = PdfPages('test.pdf')
graph = plt.title('y vs x')
plt.xlabel('x axis', fontsize = 13)
plt.ylabel('y axis', fontsize = 13)
pp.savefig(graph)
function_plot(x1,y1)
function_plot(x2,y2)
I know that my ideas are scrambled but I can't find the way to write my code. The thing is that I need my graphs to have labeled x and y axis.
我知道我的想法被打乱了,但我找不到编写代码的方法。问题是我需要我的图表标记 x 和 y 轴。
采纳答案by aloha
I was able to solve it. My mistake was that pp.savefig()should not take arguments.
我能够解决它。我的错误是pp.savefig()不应该争论。
Here is my final code:
这是我的最终代码:
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt
x1 = np.arange(10)
y1 = x1**2
x2 = np.arange(20)
y2 = x2**2
pp = PdfPages('test.pdf')
def function_plot(X,Y):
plt.figure()
plt.clf()
plt.plot(X,Y)
plt.title('y vs x')
plt.xlabel('x axis', fontsize = 13)
plt.ylabel('y axis', fontsize = 13)
pp.savefig()
function_plot(x1,y1)
function_plot(x2,y2)
pp.close()
回答by M4rtini
Try this.
尝试这个。
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt
x1 = np.arange(10)
y1 = x1**2
x2 = np.arange(20)
y2 = x2**2
def function_plot(X,Y, pp):
plt.figure()
plt.clf()
plt.plot(X,Y)
graph = plt.title('y vs x')
plt.xlabel('x axis', fontsize = 13)
plt.ylabel('y axis', fontsize = 13)
pp.savefig(plt.gcf())
with PdfPages('test.pdf') as pp:
function_plot(x1,y1, pp)
function_plot(x2,y2, pp)

