Skip to main content
 首页 » 编程设计

python之教程 : automatically export vector graphic (PDF) from plotly plot

2025年01月19日9lovecherry

最近想知道plotly能不能自动导出图。不幸的是,plotly 的文档是一个笑话,该模块希望您为如此基本的功能付费。在免费版本中,只能以非矢量格式 (png) 自动导出。在这里,我想提出一个依赖 phantomjs 的解决方法。

请您参考如下方法:

第一步:生成html文件

import plotly.offline as py 
import plotly.graph_objs as go 
 
data = go.Scatter(x=[i for i in range(10)], 
                  y=[i**2 for i in range(10)], 
                  mode='lines') 
layout = go.Layout(title="First Plot", 
                   xaxis={'title':'x - axis'}, 
                   yaxis={'title':'y - axis'}) 
fig = dict(data=[data], layout=layout) 
 
py.plot(fig, 
        filename='temp.html', 
        include_plotlyjs=True, 
        output_type='file' 
       ) 

注意:这在 html 文件中包含了 plotly.js 的很大一部分。仅此一项就占用了大约 2 MB。如果需要,将 include_plotlyjs 更改为 False 并在 html 文件中引用 plotly.js:

<script src="path/to/plotly.js"></script> 

第 2 步:PhantomJS 脚本

为 phantomjs 编写一个 javascript 文件用于导出 PDF 文件:

var page = require('webpage').create(); 
var system = require('system'); 
var args = system.args; 
 
page.viewportSize = { width: args[3], height: args[4] }; 
page.clipRect = { top: 0, left: 0, width: args[3], height: args[4] }; 
 
page.open(args[1], function() { 
  page.render(args[2]); 
  phantom.exit(); 
}); 

这需要 4 个参数:html 文件的路径、输出文件路径、输出文件的宽度和高度。

第三步:从python调用PhantomJS脚本

import subprocess 
 
xSize = 1280 
ySize = 1024 
subprocess.check_output( 
    ['phantomjs', 'phantom_html_to_PDF.js', 'temp.html', out_path, str(x_Size), str(y_Size)]) 
 
#remove temporary html file 
subprocess.check_output(['rm', 'temp.html]) 

这会调用 phantomjs 并将上面的 javascript 路径、html 文件路径、输出文件路径以及宽度和高度作为参数传递

希望对大家有用