使用pyecharts拖拉,拽,创建大屏展示

如何使用pyeharts制作大屏展示或者数据驾驶舱,请按以下步骤进行制作:
1.根据pyecharts的官方中文教程,制作各种图片;
2.使用pyecharts的 Page:顺序多图,把各种图片集中在一html文件中进行展示;

注意:刚开始请使用page = Page(layout= Page.DraggablePageLayout)模式对图片进行展示;
使用该模式后,可以对产生的图片进行位置拖动并且按你的要求进行大小变化。

3.对图片布局完毕后,点网页的左上角“save config”对布局文件进行保存,此时会保存一个chart_config.json的文件;


image.png

4.使用 DraggablePageLayout 布局重新渲染图表:

def save_resize_html(
    # Page 第一次渲染后的 html 文件
    source: str = "render.html",
    # 布局配置文件
    cfg_file: types.Optional[str] = None,
    # 布局配置 dict
    cfg_dict: types.Optional[list] = None,
    # 重新生成的 .html 存放路径
    dest: str = "resize_render.html",
) -> str

5.奉上完整的代码:

# -*- coding: utf-8 -*-
"""
Created on Sat Jan  9 11:03:20 2021

@author: lam
"""


from pyecharts import options as opts
from pyecharts.charts import Bar, Grid, Line, Liquid, Page, Pie
from pyecharts.commons.utils import JsCode
from pyecharts.components import Table
from pyecharts.faker import Faker

def bar_datazoom_slider() -> Bar:
    c = (
        Bar(init_opts=opts.InitOpts(chart_id=1))
        .add_xaxis(Faker.days_attrs)
        .add_yaxis("商家A", Faker.days_values)
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-DataZoom(slider-水平)"),
            datazoom_opts=[opts.DataZoomOpts()],
        )
        
    )
    return c


def line_markpoint() -> Line:
    c = (
        Line(init_opts=opts.InitOpts(chart_id=2))
        .add_xaxis(Faker.choose())
        .add_yaxis(
            "商家A",
            Faker.values(),
            markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min")]),
        )
        .add_yaxis(
            "商家B",
            Faker.values(),
            markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkPoint"))
    )
    return c


def pie_rosetype() -> Pie:
    v = Faker.choose()
    c = (
        Pie(init_opts=opts.InitOpts(chart_id=3))
        .add(
            "",
            [list(z) for z in zip(v, Faker.values())],
            radius=["30%", "75%"],
            center=["25%", "50%"],
            rosetype="radius",
            label_opts=opts.LabelOpts(is_show=False),
        )
        .add(
            "",
            [list(z) for z in zip(v, Faker.values())],
            radius=["30%", "75%"],
            center=["75%", "50%"],
            rosetype="area",
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="Pie-玫瑰图示例"))
    )
    return c


def grid_mutil_yaxis() -> Grid:
    x_data = ["{}月".format(i) for i in range(1, 13)]
    bar = (
        Bar(init_opts=opts.InitOpts(chart_id=4))
        .add_xaxis(x_data)
        .add_yaxis(
            "蒸发量",
            [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
            yaxis_index=0,
            color="#d14a61",
        )
        .add_yaxis(
            "降水量",
            [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
            yaxis_index=1,
            color="#5793f3",
        )
        .extend_axis(
            yaxis=opts.AxisOpts(
                name="蒸发量",
                type_="value",
                min_=0,
                max_=250,
                position="right",
                axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts(color="#d14a61")
                ),
                axislabel_opts=opts.LabelOpts(formatter="{value} ml"),
            )
        )
        .extend_axis(
            yaxis=opts.AxisOpts(
                type_="value",
                name="温度",
                min_=0,
                max_=25,
                position="left",
                axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts(color="#675bba")
                ),
                axislabel_opts=opts.LabelOpts(formatter="{value} °C"),
                splitline_opts=opts.SplitLineOpts(
                    is_show=True, linestyle_opts=opts.LineStyleOpts(opacity=1)
                ),
            )
        )
        .set_global_opts(
            yaxis_opts=opts.AxisOpts(
                name="降水量",
                min_=0,
                max_=250,
                position="right",
                offset=80,
                axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts(color="#5793f3")
                ),
                axislabel_opts=opts.LabelOpts(formatter="{value} ml"),
            ),
            title_opts=opts.TitleOpts(title="Grid-多 Y 轴示例"),
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
        )
    )

    line = (
        Line()
        .add_xaxis(x_data)
        .add_yaxis(
            "平均温度",
            [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],
            yaxis_index=2,
            color="#675bba",
            label_opts=opts.LabelOpts(is_show=False),
        )
    )

    bar.overlap(line)
    return Grid().add(
        bar, opts.GridOpts(pos_left="5%", pos_right="20%"), is_control_axis_index=True
    )


def liquid_data_precision() -> Liquid:
    c = (
        Liquid(init_opts=opts.InitOpts(chart_id=5))
        .add(
            "lq",
            [0.3254],
            label_opts=opts.LabelOpts(
                font_size=50,
                formatter=JsCode(
                    """function (param) {
                        return (Math.floor(param.value * 10000) / 100) + '%';
                    }"""
                ),
                position="inside",
            ),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="Liquid-数据精度"))
    )
    return c


def table_base() -> Table:
    table = Table(chart_id='tablename')

    headers = ["City name", "Area", "Population", "Annual Rainfall"]
    rows = [
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Adelaide", 1295, 1158259, 600.5],
        ["Darwin", 112, 120900, 1714.7],
        ["Hobart", 1357, 205556, 619.5],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
    ]
    table.add(headers, rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="Table")
    )
    return table


def page_default_layout():
    page = Page(layout= Page.DraggablePageLayout, page_title= "大屏展示")
    # page = Page()
    page.add(
        bar_datazoom_slider(),
        line_markpoint(),
        pie_rosetype(),
        grid_mutil_yaxis(),
        liquid_data_precision(),
        table_base(),
    )
    page.render("temp.html")
    page.save_resize_html( 'temp.html', cfg_file= 'chart_config.json', dest= '大屏展示.html')

if __name__ == "__main__":
    page_default_layout()

注意点:
1.由于图片的布局是根据chart_config.json中图片id的对应关系进行布局,因此每张图片均需要指定其id;
如:
Bar(init_opts=opts.InitOpts(chart_id=1))
2.在本次操作工程中,发现Table类中不包含init_opts参数,可以通过修改源码,指定char_id,具体修改的代码如下:

class Table(ChartMixin):
    def __init__(self, page_title: str = CurrentConfig.PAGE_TITLE, js_host: str = "",chart_id=None):
        self.page_title = page_title
        self.js_host = js_host or CurrentConfig.ONLINE_HOST
        self.js_dependencies: OrderedSet = OrderedSet()
        self.js_functions: OrderedSet = OrderedSet()
        self.title_opts: ComponentTitleOpts = ComponentTitleOpts()
        self.html_content: str = ""
        self._component_type: str = "table"
        if chart_id:
            self.chart_id: str = chart_id
        else:
            self.chart_id: str = uuid.uuid4().hex

笔记本屏幕太小,部分截图如下:


image.png

你可能感兴趣的:(使用pyecharts拖拉,拽,创建大屏展示)