美文网首页
python3+flask+pyecharts实现自定义饼图中心

python3+flask+pyecharts实现自定义饼图中心

作者: AmanWang | 来源:发表于2020-09-17 11:37 被阅读0次

1、前述介绍

我在写一个接口自动化程序时,需要将执行的结果按分组展示出来,最终选定了pyecharts的饼图来实现,样式如下图:


微信截图_20200917110536.png

一切都很顺利,但是最后在如何设置饼图中间的文案样式上遇到难题:中间的文案和Tooltip中的文案默认是一样的,由于中间的文案要分类换行,导致一直无法达到想要的效果,要么中间的文案“成功”“失败”后面无法加数字,要么就是Tooltip里的文案会显示“成功:56:56”这样。还出现过成功和失败的颜色不是按预设值的渲染的,甚是烦恼。
解决:后来在一个pyecharts技术群里询问解决方案,有一个朋友给了一个思路,按着他的思路尝试了几次,成功了。现在把这部分代码抽离出来分享给大家,希望能帮到大家。

2、代码结构

由于只抽离了pyecharts相关的代码,单独新建了一个测试项目,代码结构如下:


示例代码结构.png

3、源码

myFunc.py

#encoding: utf-8
from pyecharts import options as opts
from pyecharts.charts import Pie


# 定义中间文案的函数,设置样式,传参是根据我的实际需要设置的,可根据自己的实际需求更换
def new_label_opts(planName, runTime, succCount, failCount):
    msgCenter = '%s\n\n%s\n成功:%d\n失败:%d' %(planName, runTime, succCount, failCount)
    op = opts.LabelOpts(
        position="center",
        color='black',
        is_show=True,
        font_size=13,
        font_style='normal',
        font_weight='lighter',
        font_family='新宋体',
        formatter=msgCenter
    )
    return op

# 定义pyecharts主函数,传参为datas数据集合
def myCharts(datas):
    if not isinstance(datas, (tuple, list)):
        return 'datas的数据类型必须为列表或者元组'

    c = Pie()
    row_1_x_start = 10
    row_1_y_start = 20
    pieNum = min(15, len(datas))
    countPie = 0
    for i in range(0,3):
        for j in range(0, 5):
            row_1_x = str(row_1_x_start + 20*j) + "%"
            row_1_y = str(row_1_y_start + 30*i) + "%"
            if countPie < pieNum:
                plan_name = plan_name_tem = str(datas[countPie][0])
                run_time = str(datas[countPie][3])
                succCount = datas[countPie][1]
                failCount = datas[countPie][2]

                if len(plan_name) < 18:
                    plan_name = plan_name[:9] + '\n' + plan_name[9:17]
                else:
                    plan_name = plan_name[:9] + '\n' + plan_name[9:17] + '...'
                c.add(
                    plan_name_tem,
                    data_pair=[list(z) for z in zip(['成功', '失败'], [succCount, failCount])],
                    center=[row_1_x, row_1_y],
                    radius=[75, 120],
                    label_opts=new_label_opts(plan_name, run_time, succCount, failCount),
                )

                countPie += 1
            else:
                break
    c.set_colors(["#32CD32", "#FF0000"])
    c.set_global_opts(
        legend_opts=opts.LegendOpts(is_show=False),
    )
    c.set_series_opts(
        tooltip_opts=opts.TooltipOpts(
            trigger="item", formatter="{a}<br/>{b}:{c}({d}%)"
        ),
    )
    return c

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>饼状图测试</title>
    <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
    <div style="font-size: 20pt; padding-left: 37%;">
        <span>饼状图测试</span>
        <a style="font-size: 10pt; text-decoration:none;" href="/">30秒自动加载数据(或点击刷新)</a>
    </div>
    <div id="pie" style="width:100%; height:900px;"></div>
    <script>
        var chart = echarts.init(document.getElementById('pie'), 'white', {renderer: 'canvas'});
        $(
            function () {
                fetchData(chart);
                setInterval(fetchData, 30000);
            }
        );

        function fetchData() {
            $.ajax({
                type: "GET",
                url: "/pieChart/",
                dataType: 'json',
                success: function (result) {
                    chart.setOption(result);
                }
            });
        }
    </script>
</body>
</html>

app.py

from flask import Flask, render_template
from myFunc import myCharts



app = Flask(__name__, static_folder="templates")


@app.route("/")
def index():
    return render_template("index.html")

import random
@app.route("/pieChart/")
def get_pie_chart():
    datas = (
        ('中华人民共和国', random.randint(50, 100), random.randint(0, 20), '2020-09-16 15:54:23'),
        ('今年是中华人民共和国成立的第70周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2020-09-16 12:14:23'),
        ('今年是中华人民共和国成立的第69周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2020-07-15 11:54:23'),
        ('今年是中华人民共和国成立的第68周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2022-09-15 18:54:21'),
        ('今年是中华人民共和国成立的第67周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2010-09-15 12:54:09'),
        ('今年是中华人民共和国成立的第66周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2020-09-15 14:23:23'),
        ('今年是中华人民共和国成立的第65周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2020-08-15 10:24:23'),
        ('今年是中华人民共和国成立的第64周年,祝福祖国!', random.randint(50, 100), random.randint(0, 20), '2020-09-25 17:54:23'),
    )
    c = myCharts(datas)
    return c.dump_options_with_quotes()

if __name__ == "__main__":
    app.run()

4、启动flask服务及查看结果

启动后访问 http://127.0.0.1:5000/
最终结果:见上面第一张图

E:\testPyecharts>python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

相关文章

网友评论

      本文标题:python3+flask+pyecharts实现自定义饼图中心

      本文链接:https://www.haomeiwen.com/subject/ceclyktx.html