教程:自动从 plotly plot 中导出矢量图形 (PDF)
Tutorial: automatically export vector graphic (PDF) from plotly plot
最近在想plotly能不能自动导出图。不幸的是,plotly 的文档是一个笑话,该模块希望您为如此基本的功能付费。在免费版本中,只能以非矢量格式 (png) 自动导出。在这里我想提出一个依赖 phantomjs 的解决方法。
第 1 步:生成 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'
)
注意:这将 plotly.js 的大部分内容包含在 html 文件中。仅此一项就占用了大约 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 文件的路径、输出文件路径、输出文件的宽度和高度。
第 3 步:从 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 文件路径、输出文件路径以及宽度和高度作为参数传递
我希望这对某人有用
最近在想plotly能不能自动导出图。不幸的是,plotly 的文档是一个笑话,该模块希望您为如此基本的功能付费。在免费版本中,只能以非矢量格式 (png) 自动导出。在这里我想提出一个依赖 phantomjs 的解决方法。
第 1 步:生成 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'
)
注意:这将 plotly.js 的大部分内容包含在 html 文件中。仅此一项就占用了大约 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 文件的路径、输出文件路径、输出文件的宽度和高度。
第 3 步:从 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 文件路径、输出文件路径以及宽度和高度作为参数传递
我希望这对某人有用