博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
后端使用pyecharts画图并输出为图片保存
阅读量:3950 次
发布时间:2019-05-24

本文共 8893 字,大约阅读时间需要 29 分钟。

                       

带区域标注的线图

#coding=utf-8from __future__ import unicode_literalsfrom pyecharts import Linefrom pyecharts.conf import PyEchartsConfigfrom pyecharts.engine import EchartsEnvironmentfrom pyecharts.utils import write_utf8_html_fileattr = ["2018/03/11", "2018/03/18", "2018/03/25", "2018/04/01", "2018/04/08"]selectedColumn = "Visitor Count"column = 'Column: {}'.format(selectedColumn)line = Line(column)v1 = [661.0, 359.0, 358.0, 536.0, 391.0]v2 = [102.0, 906.0, 84.0, 878.0, 115.0]line.add("VP1", attr,v1 ,mark_point=["average", "max", "min"])line.add("VP2", attr, v2,mark_point=["average", "max", "min"])line.add("Filter", attr, [430]*len(v1), is_fill=True,          area_opacity=0.3, is_smooth=True)#,is_toolbox_show=Falseconfig = PyEchartsConfig(echarts_template_dir='./')env = EchartsEnvironment(pyecharts_config=config)tpl = env.get_template('chart_template.html')html = tpl.render(line=line)write_utf8_html_file('chart_out.html', html)  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

模板文件内容

        
   
    Visitor Record echarts    {
{ echarts_js_dependencies(line) }}    {
{ echarts_container(line) }}    {
{ echarts_js_content(line) }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

运行结果(chart_out.html):

这里写图片描述

以上基本的使用就OK了,但是我们的需求是将页面中的canvas保存为图片,下面将介绍我最近项目中使用的一种方法:

使用到的工具是

这里写图片描述

具体安装就不多说了

phantomjs --helpUsage:   phantomjs [switchs] [options] [script] [argument [argument [...]]]Options:  --cookies-file=
                 Sets the file name to store the persistent cookies  --config=
                       Specifies JSON-formatted configuration file  --debug=
                        Prints additional warning and debug message: 'true' or 'false' (default)  --disk-cache=
                   Enables disk cache: 'true' or 'false' (default)  --disk-cache-path=
              Specifies the location for the disk cache  --ignore-ssl-errors=
            Ignores SSL errors (expired/self-signed certificate errors): 'true' or 'false' (default)  --load-images=
                  Loads all inlined images: 'true' (default) or 'false'  --local-url-access=
             Allows use of 'file:///' URLs: 'true' (default) or 'false'  --local-storage-path=
           Specifies the location for local storage  --local-storage-quota=
          Sets the maximum size of the local storage (in KB)  --offline-storage-path=
         Specifies the location for offline storage  --offline-storage-quota=
        Sets the maximum size of the offline storage (in KB)  --local-to-remote-url-access=
   Allows local content to access remote URL: 'true' or 'false' (default)  --max-disk-cache-size=
          Limits the size of the disk cache (in KB)  --output-encoding=
              Sets the encoding for the terminal output, default is 'utf8'  --remote-debugger-port=
         Starts the script in a debug harness and listens on the specified port  --remote-debugger-autorun=
      Runs the script in the debugger immediately: 'true' or 'false' (default)  --proxy=
                        Sets the proxy server, e.g. '--proxy=http://proxy.company.com:8080'  --proxy-auth=
                   Provides authentication information for the proxy, e.g. ''-proxy-auth=username:password'  --proxy-type=
                   Specifies the proxy type, 'http' (default), 'none' (disable completely), or 'socks5'  --script-encoding=
              Sets the encoding used for the starting script, default is 'utf8'  --script-language=
              Sets the script language instead of detecting it: 'javascript'  --web-security=
                 Enables web security, 'true' (default) or 'false'  --ssl-protocol=
                 Selects a specific SSL protocol version to offer. Values (case insensitive): TLSv1.2, TLSv1.1, TLSv1.0, TLSv1 (same as v1.0), SSLv3, or ANY. Default is to offer all that Qt thinks are secure (SSLv3 and up). Not all values may be supported, depending on the system OpenSSL library.  --ssl-ciphers=
                  Sets supported TLS/SSL ciphers. Argument is a colon-separated list of OpenSSL cipher names (macros like ALL, kRSA, etc. may not be used). Default matches modern browsers.  --ssl-certificates-path=
        Sets the location for custom CA certificates (if none set, uses environment variable SSL_CERT_DIR. If none set too, uses system default)  --ssl-client-certificate-file=
  Sets the location of a client certificate  --ssl-client-key-file=
          Sets the location of a clients' private key  --ssl-client-key-passphrase=
    Sets the passphrase for the clients' private key  --webdriver=
                    Starts in 'Remote WebDriver mode' (embedded GhostDriver): '[[
:]
]' (default '127.0.0.1:8910')   --webdriver-logfile=
            File where to write the WebDriver's Log (default 'none') (NOTE: needs '--webdriver')   --webdriver-loglevel=
           WebDriver Logging Level: (supported: 'ERROR', 'WARN', 'INFO', 'DEBUG') (default 'INFO') (NOTE: needs '--webdriver')   --webdriver-selenium-grid-hub=
  URL to the Selenium Grid HUB: 'URL_TO_HUB' (default 'none') (NOTE: needs '--webdriver')   -w,--wd                              Equivalent to '--webdriver' option above  -h,--help                            Shows this message and quits  -v,--version                         Prints out PhantomJS versionAny of the options that accept boolean values ('true'/'false') can also accept 'yes'/'no'.Without any argument, PhantomJS will launch in interactive mode (REPL).Documentation can be found at the web site, http://phantomjs.org. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

实现过程:

使用pyecharts生成一个html文件,然后利用phantomjs无头浏览器打开页面执行操作,用法为:

cmd = ["phantomjs", genImgJs, outPutHtml, outPutImg]try:    subprocess.check_output(cmd, stderr=subprocess.STDOUT)except subprocess.CalledProcessError as err:    print err  
1
2
3
4
5

关于那个作为参数的js文件:

"use strict";var page = require('webpage').create(),    system = require('system'),    address, output, size, pageWidth, pageHeight;if (system.args.length < 3 || system.args.length > 5) {    console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');    console.log('  paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');    console.log('  image (png/jpg output) examples: "1920px" entire page, window width 1920px');    console.log('                                   "800px*600px" window, clipped to 800x600');    phantom.exit(1);} else {    address = system.args[1];    output = system.args[2];    page.viewportSize = { width: 500, height: 380 };    if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {        size = system.args[3].split('*');        page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }                                           : { format: system.args[3], orientation: 'portrait', margin: '1cm' };    } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {        size = system.args[3].split('*');        if (size.length === 2) {            pageWidth = parseInt(size[0], 10);            pageHeight = parseInt(size[1], 10);            page.viewportSize = { width: pageWidth, height: pageHeight };            page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };        } else {            console.log("size:", system.args[3]);            pageWidth = parseInt(system.args[3], 10);            pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any            console.log ("pageHeight:",pageHeight);            page.viewportSize = { width: pageWidth, height: pageHeight };        }    }    if (system.args.length > 4) {        page.zoomFactor = system.args[4];    }    page.open(address, function (status) {        if (status !== 'success') {            console.log('Unable to load the address!');            phantom.exit(1);        } else {            window.setTimeout(function () {                page.render(output);                phantom.exit();            }, 1200);        }    });}  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

更为完整一点的后端代码(django框架内):

config = PyEchartsConfig(echarts_template_dir=STATIC_ROOT)env = EchartsEnvironment(pyecharts_config=config)tpl = env.get_template('chart_template.html')html = tpl.render(line=line)outHtml = '{}.html'.format(col)outPutHtml = os.path.join(STATIC_ROOT, outHtml)write_utf8_html_file(outPutHtml, html)genImgJs = os.path.join(STATIC_ROOT, 'js/genImg.js')imageName = 'images/{}.png'.format(title+col)outPutImg = os.path.join(STATIC_ROOT,imageName )cmd = ["phantomjs", genImgJs, outPutHtml, outPutImg]try:    subprocess.check_output(cmd, stderr=subprocess.STDOUT)except subprocess.CalledProcessError as err:    print err  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!

你可能感兴趣的文章
2017新浪微整形年度大数据报告
查看>>
实战 | 用 Python 选股票,据说可以多挣个20%
查看>>
重磅 | 数据挖掘之父韩家炜:文本语料库的数据挖掘(附视频+PPT下载)
查看>>
干货汇总 | 你可能不知道的 Python Web 部署方式总结
查看>>
技术人再不懂区块链,你就OUT了?漫画版
查看>>
快收藏!史上最全的 Linux Shell 文本处理工具集锦
查看>>
一小时爬千万数据的新浪微博爬虫
查看>>
简约而不简单的 Django 新手图文教程
查看>>
重磅!阿里首次全面公开展示AI布局(附布局图/成绩单/六产业详解)
查看>>
谷歌大脑2017技术研究总结 | Jeff Dean执笔(附论文 & 数据集)
查看>>
最新中国一二三四五线城市排名出炉!去这些城市买房准没错!
查看>>
BAT人工智能生态时局图:全面战争爆发前夜
查看>>
Python交互式数据分析报告框架~Dash介绍
查看>>
Chrome 浏览器 必知必会的小技巧
查看>>
Python奇技淫巧,看看你知道几个
查看>>
资源&教程 | Python数据分析,详细的学习路径
查看>>
白话AI:看懂深度学习真的那么难吗?初中数学,就用10分钟
查看>>
中国癌症大数据出来了!每年126万例癌症死亡本可避免
查看>>
超全的 Linux 机器的渗透测试命令备忘表,共16表128条命令
查看>>
代码传奇 | 明明可以靠颜值 却用代码把人类送上了月球的女人——Margaret Hamilton
查看>>