Quickly draw a dynamic sorting diagram-Pyecharts advanced component Timeline implementation!

I wrote a tutorial on how to make a dynamic sorting graph in Python. It uses the animation function in Matplotlib. For the content of the article, please refer to the detailed tutorial for making a dynamic sorting graph. The final part of the dynamic ranking graph is as follows:

save_bar1.gif

Today's article will use another Python software package Pyecharts to achieve similar effects. The effects are as follows:

save_bar.gif

In the entire drawing process of dynamic graphs, Pyecharts' Timeline advanced component is mainly used, which has the same principle as the animatation function in Matplotlib.

The data uses time as the only variable, and other data items are different at different time points. A visualization chart can be drawn at a time point, and all the visualization charts can be connected frame by frame. The data difference changes, and finally a dynamic graph effect is formed

The role played by the Timeline component and the anaimation function here is the splicing of visual charts between frames. After the above principles have been introduced, let’s introduce how to use Timeline.

Timeline component usage

**1, install Pyecharts **

Before using, please make sure you have installed Pyecharts. The installation method is to use the pip tool directly, the command is as follows:

pip install pyechartske

2. Create a Timeline object class

First create a Timeline object, which is equivalent to a container, put each frame of visualization report diagram drawn later in it, and then synthesize a video similar to a dynamic diagram according to the order of placement

# 导入所需要的库函数
from pyecharts import options as opts
from pyecharts.charts import Bar,Timeline
from pyecharts.faker import Faker
import random

t1  = Timeline()# 创建 Timeline对象

3. Draw each frame of the chart in a loop and put it in the Timeline

Use the for or while loop statement, follow the Pyecharts statement to create a visual chart corresponding to each frame time, and then add it to the Timeline() component created earlier. Here the chart uses the histogram Bar as an example

for i in range(1969,2020):
    attr1 = random.shuffle(list(attr))
    bar = (
    Bar()
    .add_xaxis(random.sample(attr, len(attr)))
    .add_yaxis('Data',Faker.values(),label_opts = opts.LabelOpts(position = 'right'),
             )
    .set_series_opts(label_opts = opts.LabelOpts(is_show = True,position = 'right'))
    .reversal_axis()
    .set_global_opts(title_opts = opts.TitleOpts("{}".format(i),
                                                 pos_left = '50%',

                                                ),
                    legend_opts = opts.LegendOpts(pos_right = '10%'))

    )

    t1.add(bar,'{}年'.format(i))

Interpretation of the code, in order to herein as the period 1969-2020, in a given year is created corresponding to each time Bar graph nodes, and finally to t1.add(instance,str)a function is added to the chart corresponding to the created time point Timelinecomponents, in order to better show the back of dynamic effects , Here is the inverse operation ( reversal_axis()) on the coordinate axis of Bar, the preview of the effect of each frame is as follows:

2222.png

4. Beautify and render charts, html files

Further, a function Timeline () are add_schema()used to beautify assembly styles, such 时间轴方向、符号、颜色、每一帧停留时间、播放键位置、是否现实 timeline 组件、组件位置other properties, functions described below using

def add_schema(
    # 坐标轴类型。可选:
    # 'value': 数值轴,适用于连续数据。
    # 'category': 类目轴,适用于离散的类目数据,为该类型时必须通过 data 设置类目数据。
    # 'time': 时间轴,适用于连续的时序数据,与数值轴相比时间轴带有时间的格式化,在刻度计算上也有所不同,
    # 例如会根据跨度的范围来决定使用月,星期,日还是小时范围的刻度。
    # 'log' 对数轴。适用于对数数据。
    axis_type: str = "category",

    # 时间轴的类型。可选:
    # 'horizontal': 水平
    # 'vertical': 垂直
    orient: str = "horizontal",

    # timeline 标记的图形。
    # ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 
    # 'pin', 'arrow', 'none'
    # 可以通过 'image://url' 设置为图片,其中 URL 为图片的链接,或者 dataURI。
    symbol: Optional[str] = None,

    # timeline 标记的大小,可以设置成诸如 10 这样单一的数字,也可以用数组分开表示宽和高,
    # 例如 [20, 10] 表示标记宽为 20,高为 10。
    symbol_size: Optional[Numeric] = None,

    # 表示播放的速度(跳动的间隔),单位毫秒(ms)。
    play_interval: Optional[Numeric] = None,

    # 表示播放按钮的位置。可选值:'left'、'right'。
    control_position: str = "left",

    # 是否自动播放。
    is_auto_play: bool = False,

    # 是否循环播放。
    is_loop_play: bool = True,

    # 是否反向播放。
    is_rewind_play: bool = False,

    # 是否显示 timeline 组件。如果设置为 false,不会显示,但是功能还存在。
    is_timeline_show: bool = True,

    # 是否反向放置 timeline,反向则首位颠倒过来
    is_inverse: bool = False,

    # Timeline 组件离容器左侧的距离。
    # left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,
    # 也可以是 'left', 'center', 'right'。
    # 如果 left 的值为'left', 'center', 'right',组件会根据相应的位置自动对齐
    pos_left: Optional[str] = None,

    # timeline 组件离容器右侧的距离。
    # right 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    pos_right: Optional[str] = None,

    # Timeline 组件离容器上侧的距离。
    # left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,
    # 也可以是 'top', 'middle', 'bottom'。
    # 如果 left 的值为 'top', 'middle', 'bottom',组件会根据相应的位置自动对齐
    pos_top: Optional[str] = None,

    # timeline 组件离容器下侧的距离。
    # bottom 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    pos_bottom: Optional[str] = "-5px",

    # 时间轴区域的宽度, 影响垂直的时候时间轴的轴标签和轴之间的距离
    width: Optional[str] = None,

    # 时间轴区域的高度
    height: Optional[str] = None,

    # 时间轴的坐标轴线配置,参考 `series_options.LineStyleOpts`
    linestyle_opts: Union[opts.LineStyleOpts, dict, None] = None,

    # 时间轴的轴标签配置,参考 `series_options.LabelOpts`
    label_opts: Optional[opts.LabelOpts] = None,

    # 时间轴的图形样式,参考 `series_options.ItemStyleOpts`
    itemstyle_opts: Union[opts.ItemStyleOpts, dict, None] = None,
)

After beautifying the chart, use the rendering command to transfer the chart everywhere to the local html file t1.render( html路径). The final effect is as follows ( Ps: Please don’t care about the authenticity of the data in the chart. This is just to introduce the use of Timeline(). The data inside are all randomly generated Of )

save_bar.gif

Complete code part

from pyecharts import options as opts
from pyecharts.charts import Bar,Timeline
from pyecharts.faker import Faker
import random

attr = Faker.choose()
t1  = Timeline()# 创建 Timeline对象

for i in range(1969,2020):
    attr1 = random.shuffle(list(attr))
    bar = (
    Bar()
    .add_xaxis(random.sample(attr, len(attr)))
    .add_yaxis('Data',Faker.values(),label_opts = opts.LabelOpts(position = 'right'),
             )
    .set_series_opts(label_opts = opts.LabelOpts(is_show = True,position = 'right'))
    .reversal_axis()
    .set_global_opts(title_opts = opts.TitleOpts("{}".format(i),
                                                 pos_left = '50%',

                                                ),
                    legend_opts = opts.LegendOpts(pos_right = '10%'))

    )

    t1.add(bar,'{}年'.format(i))
t1.add_schema(
symbol = 'arrow',# 设置标记时间;
    #orient = 'vertical',
     symbol_size = 2,# 标记大小;
    play_interval = 900,# 播放时间间隔;
    control_position = 'right',# 控制位置;
linestyle_opts = opts.LineStyleOpts(width = 5,
                                   type_ = 'dashed',
                                   color = 'rgb(255,0,0,0.5)'),
    label_opts = opts.LabelOpts(color = 'rgb(0,0,255,0.5)',
                                    font_size = 15,
                                    font_style = 'italic',
                                    font_weight = 'bold',
                                     font_family ='Time New Roman',

                                position = 'left',
                                interval = 20,
                                    )
)
t1.render("D:/timeline_bar.html")

Timeline component extension

The Timeline component is introduced above by making a dynamic sequence diagram. In this case, the main type of the chart is Bar, but in actual applications, Bar can be replaced with other chart types according to different application scenarios such as visual effects and business requirements. You only need to replace the above code part Replace the main code of the for loop in

for i in range(1969,2020):
    attr1 = random.shuffle(list(attr))
    instance = ...你的图表类型
    t1.add(instance,'{}年'.format(i))

Changing a chart type may have a different visual effect, such as a mulberry chart:

imag11252.gif

The doughnut pie chart has good dynamic effects, which can be realized by the Timeline component

imag112521.gif

Okay, the above is all the content of this article, and thank you all for reading!

Guess you like

Origin blog.csdn.net/weixin_42512684/article/details/108176613