Beispiel #1
0
def render_map(date_list, cy_name_list, ncov_data) -> Map:
    tl = Timeline()
    tl.add_schema(is_auto_play=True,
                  play_interval=60,
                  is_loop_play=False,
                  width=700)
    for date_str in date_list:
        map_ = (Map(init_opts=opts.InitOpts(
            bg_color='rgba(255,250,205,0.2)',
            width='1000px',
            height='600px',
            page_title='page',
            theme=ThemeType.MACARONS)).add(
                "全球疫情变化",
                [list(z) for z in zip(cy_name_list, ncov_data[date_str])],
                "world",
                is_map_symbol_show=False,
                name_map=countries_dict).set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                        title_opts=opts.TitleOpts(title="19-nCoV\n%s" %
                                                  date_str),
                        legend_opts=opts.LegendOpts(is_show=False),
                        visualmap_opts=opts.VisualMapOpts(max_=3000)))
        tl.add(map_, "%s" % date_str)
    tl.render("nCoV全球疫情地图({}).html".format(datetime.date.today()))
Beispiel #2
0
def get_index():
    timeline = Timeline(
        # init_opts=opts.InitOpts(width="1600px", height="900px", theme=ThemeType.DARK)
        init_opts=opts.InitOpts(
            width="100vw", height="100vh", theme=ThemeType.DARK))

    for day in date_list:
        g = get_week_chart(date=day)
        timeline.add(g, time_point=day)

    timeline.add_schema(
        orient="vertical",
        is_auto_play=True,
        is_inverse=True,
        play_interval=2000,
        pos_left="null",
        pos_right="20",
        pos_top="10",
        pos_bottom="10",
        width="60",
        label_opts=opts.LabelOpts(is_show=False, color="#fff"),
    )
    # timeline.render("china_gdp_from_1993_to_2018.html")
    return render_template(
        "demo.html",
        # passed_data=msg_data,
        myechart=timeline.render_embed(),
    )
Beispiel #3
0
def charts():
    fp = open('./oldData.txt', 'r')

    # Timeline
    timeline = Timeline(init_opts=opts.InitOpts(
        width="1660px",
        height="708px",
    ))

    # 48 bar charts
    for i in range(48):
        X, Y, Color = getSta(fp)

        # y-axle with color
        y = []
        for j in range(22):
            y.append(
                opts.BarItem(
                    name=X[j],
                    value=Y[j],
                    itemstyle_opts=opts.ItemStyleOpts(color=Color[j])))

        # single bar chart
        bar = (
            Bar().add_xaxis(X).add_yaxis(
                "Youbike 使用率", y).reversal_axis().set_global_opts(
                    title_opts=opts.TitleOpts(
                        title="南港區Youbike的一天",
                        pos_left="center",
                    ),
                    legend_opts=opts.LegendOpts(pos_left="left"),
                    graphic_opts=[
                        opts.GraphicGroup(  # add a block
                            graphic_item=opts.GraphicItem(left="80%",
                                                          top="80%"),
                            children=[
                                opts.GraphicText(  # add text into the block
                                    graphic_item=opts.GraphicItem(
                                        left="center",
                                        top="center",
                                        # z=100
                                    ),
                                    graphic_textstyle_opts=opts.
                                    GraphicTextStyleOpts(
                                        text="{}".format(invTime[i]),
                                        font="48px Verdana",
                                    ),
                                )
                            ])
                    ]).set_series_opts(  # number showed at right of the bar
                        label_opts=opts.LabelOpts(position="right",
                                                  color="#333")))
        timeline.add(bar, "")  # add single bar chart into timeline
        timeline.add_schema(play_interval=1000,
                            is_loop_play=True)  # play settings

    # export into HTML
    timeline.render("YoubikeUsingRate.html")

    fp.close()
def get_grid_timeline(column, label, df_city, df_province, df_cn, min_num,
                      max_num, range_color):
    pass
    timeline = Timeline(init_opts=opts.InitOpts(
        width="1500px", height="850px", theme=ThemeType.DARK))
    time_list = df_city['date'].unique().tolist()
    for y in time_list:
        g = gird_chart(column=column,
                       label=label,
                       target_date=y,
                       df_city=df_city,
                       df_province=df_province,
                       df_cn=df_cn,
                       min_num=min_num,
                       max_num=max_num,
                       range_color=range_color)
        timeline.add(g, time_point=str(y))

    timeline.add_schema(
        orient="vertical",
        #         is_auto_play=True,
        is_inverse=True,
        play_interval=5000,
        pos_left="null",
        pos_right="5",
        pos_top="20",
        pos_bottom="20",
        width="60",
        label_opts=opts.LabelOpts(is_show=False, color="#fff"),
    )
    return timeline
Beispiel #5
0
def theme_macarons(make_new, tag):
    tl = Timeline(init_opts=opts.InitOpts(
        theme=ThemeType.MACARONS))  # theme=ThemeType.PURPLE_PASSION
    tl.add_schema(
        pos_bottom='-7px',
        is_auto_play=True,
        symbol_size=[20, 20],
        play_interval=2000,
    )
    for i in range(2015, 2020):
        bar = Bar()
        bar.add_xaxis(list(make_new.columns))
        bar.add_yaxis("",
                      list(make_new.loc[i, :].values),
                      label_opts=opts.LabelOpts(is_show=False))
        bar.set_colors([
            random.choice([
                'blue', 'rgba(100,255,0,0.8)', '#5793f3', '#007A99', 'yellow'
            ])
        ])
        bar.set_global_opts(
            xaxis_opts=opts.AxisOpts(name="", axislabel_opts={"rotate": 40}),
            title_opts=opts.TitleOpts("{}-{}指数".format(i, tag)))

        tl.add(bar, "{}年".format(str(i)))
    return tl
def draw_Timeline(Time_List, Score_List, Update_List):
	#生成时间线对象
	t1 = Timeline(init_opts=opts.InitOpts(width = '1600px', height = '700px', theme = ThemeType.LIGHT))
	temp_Time_List = []
	temp_Score_List = []
	#配置时间轴参数
	t1.add_schema(axis_type = 'time', symbol_size = [10,10], is_auto_play = True,
						 width = '1000px', height = '200px', pos_bottom = '-120px', pos_left = '350px')

	for update_time in Update_List:
		for index in range(0,len(Time_List)):
			#判断每一条评论的时间处于的版本区间
			if compare_time(update_time, Time_List[index]):
				temp_Time_List.append(Time_List[index])
				temp_Score_List.append(Score_List[index])
			else:
				break
		#绘制折线并添加到时间线中
		line = (
			Line(init_opts=opts.InitOpts(theme = ThemeType.LIGHT, width = '1200px', height = '300px'))
			.add_xaxis(temp_Time_List)
			.add_yaxis("情感值", temp_Score_List, is_smooth = True, is_symbol_show = False)
			.set_global_opts(
				yaxis_opts=opts.AxisOpts(name="情感值", name_textstyle_opts = opts.TextStyleOpts(font_size = 18)),
				xaxis_opts=opts.AxisOpts(name="时间", name_textstyle_opts = opts.TextStyleOpts(font_size = 18)),
				legend_opts=opts.LegendOpts(is_show = False)
				)
				)
		t1.add(line, update_time)
		temp_Time_List = []
		temp_Score_List = []
	return t1
def TimelinePie(data_nums: dict):
    '''
    我自己选的八个出版社的年出版量对比\n
    :param data_nums: 字典,键为年份,值是列表,存放各出版社的出版数量
    :return: 不存在
    '''
    global dir_to_save
    attr = ['机械工业出版社', '人民邮电出版社', '电子工业出版社',
            '清华大学出版社', '人民文学出版社', '上海译文出版社',
            '生活·读书·新知三联书店', '广西师范大学出版社']
    tl = Timeline()
    for i in tqdm(range(2002, 2015)):
        pie = (
            Pie()
                .add(
                "",
                [list(z) for z in zip(attr, data_nums[i])],
                rosetype="radius",
                radius=["30%", "55%"],
            )
                .set_global_opts(title_opts=opts.TitleOpts("8个出版社的{}年出版量对比".format(i),
                                                           pos_top='15%')
                                 )
        )
        tl.add(pie, "{}年".format(i))
    tl.add_schema(is_auto_play=True, play_interval=1000)
    tl.render(dir_to_save + "TypicalPublishers_timeline_pie.html")
    print("Successfully drew TypicalPublishers_timeline_pie")
Beispiel #8
0
def get_whole_chart():
    timeline = Timeline(
        init_opts=opts.InitOpts(
            width="1600px", height="900px", theme=ThemeType.DARK,
            page_title='新冠肺炎疫情地图',)
    )
    for i in range(len(date_list)):

        g = get_date_chart(date=date_list[i])

        timeline.add(
            g,
            time_point=simple_date_list[i]
        )

    timeline.add_schema(
        orient="vertical",
        is_auto_play=True,
        is_inverse=True,
        play_interval=2000,
        pos_left="null",
        pos_right="5",
        pos_top="20",
        pos_bottom="20",
        width="70",
        label_opts=opts.LabelOpts(
            is_show=True,
            color="#fff"
        ),
    )

    return timeline
Beispiel #9
0
def gcv_main():
    """
    TODO
    """
    # 生成时间轴的图
    timeline = Timeline(
        init_opts=opts.InitOpts(width="1600px", height="800px"))

    commit_log = repo_analyze()

    contribute = {}

    for item in commit_log.itertuples():
        top_commiter = get_topX(contribute, item, 5)

        timeline.add(get_commits_chart(time=item[1], \
                names=top_commiter['author'].tolist(), \
                c_insert=top_commiter['v1'].tolist(), \
                c_delete=top_commiter['v2'].tolist(), \
                c_add=top_commiter['v0'].tolist()), \
                time_point=item[1])

    # 1.0.0 版本的 add_schema 暂时没有补上 return self 所以只能这么写着
    timeline.add_schema(is_auto_play=True, play_interval=100)
    timeline.render("git.html")
Beispiel #10
0
def timeline_suicides():
    t1 = Timeline()
    for i in range(1985, 2016):
        bar = (Bar(init_opts=opts.InitOpts(
            theme=ThemeType.ROMA)).add_xaxis(country20).add_yaxis(
                "15-24 years",
                shujizonghe[i][0::5]).add_yaxis("25-34 years",
                                                shujizonghe[i][1::5]).
               add_yaxis("35-54 years", shujizonghe[i][2::5]).add_yaxis(
                   "55-74 years", shujizonghe[i][3::5]).add_yaxis(
                       "75+ years", shujizonghe[i][4::5]).set_global_opts(
                           title_opts=opts.TitleOpts("{}年男性自杀率".format(i))))
        pie = (Pie().add(
            "Austria",
            [list(z) for z in zip(age_rank, shujizonghe[i][0:5])],
            rosetype="radius",
            center=["80%", "20%"],
            radius="28%",
        ).set_global_opts(title_opts=opts.TitleOpts(title="年龄段比重")))
        bar.overlap(pie)
        t1.add(bar, "{}".format(i))
        t1.add_schema(is_auto_play=True,
                      play_interval=1000,
                      is_timeline_show=False)
    return t1
Beispiel #11
0
def show_score_top():
    # 查找上映年份集合
    showtime = select_showtime()
    # 生成时间轴的图
    timeline = Timeline(
        init_opts=opts.InitOpts(page_title="豆瓣电影TOP250-评分TOP10的电影", ))
    for year in showtime:
        film_tuple = select_film(year)
        date_list = select_data(year)
        timeline.add_schema(is_auto_play=True, play_interval=1000)
        # 柱状图初始化
        bar = Bar()
        # 横坐标
        bar.add_xaxis(film_tuple[0])
        # 纵坐标
        bar.add_yaxis(
            "",
            date_list,
            # 数据靠右显示
            label_opts=opts.LabelOpts(is_show=True, position='right'))
        # 横纵坐标翻转
        bar.reversal_axis()
        # 全局配置
        bar.set_global_opts(
            # 标题
            title_opts=opts.TitleOpts(
                title="豆瓣电影TOP250-第{}年评分TOP10的电影".format(year),
                pos_left='center'),
            # 横坐标隐藏
            xaxis_opts=opts.AxisOpts(is_show=False,
                                     max_=select_film(year)[2],
                                     min_=(float(select_film(year)[3]) - 0.1),
                                     split_number=10),
            # 纵坐标
            yaxis_opts=opts.AxisOpts(
                max_=9,
                # 字体大小
                axislabel_opts=opts.LabelOpts(font_size=10),
                # 隐藏坐标轴
                axisline_opts=opts.AxisLineOpts(is_show=False),
                # 隐藏刻度
                axistick_opts=opts.AxisTickOpts(is_show=False)))
        # 组合组件
        grid = (Grid().add(bar,
                           grid_opts=opts.GridOpts(pos_top='8%',
                                                   pos_bottom='12%',
                                                   pos_left='25%')))
        timeline.add(grid, "{}年".format(year))
        timeline.add_schema(is_auto_play=True,
                            play_interval=1000,
                            is_loop_play=False,
                            width='820px',
                            pos_left='60px')
    # 生成HTML
    html = "pages/iframes/score_top.html"
    timeline.render("./templates/" + html)
    return html
def main():
    df = pd.read_csv('../source_data.csv',
                     usecols=['date', 'country', 'confirmed'])

    # 获取顺序的日期列表
    date_list = list(set(df['date'].to_list()))
    date_list.sort()
    date_list = date_list[-20:]

    tl = Timeline()
    tl.add_schema(is_auto_play=False, play_interval=500, is_loop_play=False)
    draw_bar(df, date_list, tl)
    tl.render_notebook()
    tl.render("timeline_bar_with_graphic.html")
Beispiel #13
0
    def render_time_air(self, reversal_axis=True, pos_top='top'):
        time_line = Timeline()  # 创建 Timeline对象

        # 开始准备画图;
        for run_data in self.data_list:
            title_text = str(run_data[0]) + '_数据展示'
            run_date = run_data[0]
            x_value = [str(i) for i in run_data[1]]
            y_title = run_data[2]
            y_value = [float(i) for i in run_data[3]]
            if self.reder_type.lower() == 'Bar_Py'.lower():
                c = Bar_Py(title_text,
                           x_value,
                           y_title,
                           y_value,
                           reversal_axis=reversal_axis,
                           pos_top=pos_top).bar_render_general()
            else:
                c = Line_Py(title_text,
                            x_value,
                            y_title,
                            y_value,
                            pos_top=pos_top).line_render_air()

            time_line.add(c, run_date)
        # 画好的图加入时间线;
        time_line.add_schema(
            symbol='arrow',  # 设置标记时间;
            # orient = 'vertical',
            is_auto_play=True,
            symbol_size=2,  # 标记大小;
            play_interval=self.play_interval,  # 播放时间间隔;
            control_position=self.control_position,  # 控制位置;
            # 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
            # )
        )
        return time_line
Beispiel #14
0
def get_visualization(datatype='Confirmed',
                      increment_update=False,
                      maptype='china-cities',
                      save_png=False):
    v = Visualization(datatype=datatype,
                      increment_update=increment_update,
                      maptype=maptype)
    dates = v.dates
    dates = dates + dates[-1:] * 3

    # 增量更新图片
    if increment_update:
        for date in dates:
            if not os.path.exists(
                    f"fig/png/COVID-19_{datatype}_{maptype}_{date}.png"):
                chart = v.get_day_chart(date=date)
                make_snapshot(
                    snapshot, chart.render(),
                    f"fig/png/COVID-19_{datatype}_{maptype}_{date}.png")
    else:
        timeline = Timeline(init_opts=opts.InitOpts(
            width="1440px", height="800px", theme=ThemeType.DARK))
        for date in dates:
            if date <= '2020-01-23':
                continue
            try:
                chart = v.get_day_chart(date=date)
                timeline.add(chart, time_point=date[6:])
                if save_png:
                    make_snapshot(
                        snapshot, chart.render(),
                        f"fig/png/COVID-19_{datatype}_{maptype}_{date}.png")
            except Exception as e:
                print('get char error', date, e)

        timeline.add_schema(
            orient="vertical",
            is_auto_play=True,
            is_inverse=True,
            play_interval=1000,  #播放间隔1000ms
            pos_left="null",
            pos_right="5",
            pos_top="20",
            pos_bottom="20",
            width="60",
            label_opts=opts.LabelOpts(is_show=True, color="#fff"),
        )

        timeline.render(f"fig/html/COVID-19_{maptype}_{datatype}.html")
Beispiel #15
0
def timeline_bar() -> Timeline:
    x = ['国内', '国外']
    tl = Timeline()
    tl.add_schema(is_auto_play=True, play_interval=5000, is_loop_play=True)
    k = 0

    for j in date:
        bar = (Line().add_xaxis(date).add_yaxis("国内", hs(c1, k)).add_yaxis(
            "国外", hs(c, k)).extend_axis(yaxis=opts.AxisOpts()).set_series_opts(
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts("{}国内外疫情趋势".format(j))))

        k = k + 1
    return tl
Beispiel #16
0
def class_history_grade(class_index: int) -> Timeline:
    if class_subject(class_index) == '理科':
        ranking_max = 17
    else:
        ranking_max = 3
    # TODO  文科班主科分开排序
    tl = Timeline(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE, width='100%'))
    tl.add_schema(is_auto_play=True, play_interval=1500)
    for test in Test.query.all():
        cag: ClassAverageGrade = ClassAverageGrade.query.filter(
            ClassAverageGrade.test_time == test.test_time,
            ClassAverageGrade.class_index == class_index,
        ).first()
        grades = [cag.chinese, cag.math, cag.english,
                  cag.physics, cag.chemistry, cag.biology, ]
        rankings = [cag.chinese_ranking, cag.math_ranking, cag.english_ranking,
                    cag.physics_ranking, cag.chemistry_ranking, cag.biology_ranking, ]
        grade_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))
                .add_xaxis(['语文', '数学', '英语', '物理', '化学', '生物'])
                .add_yaxis('Grade', grades)
                .extend_axis(
                yaxis=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(formatter="{value} 名"),
                    min_=0, max_=ranking_max, interval=2,
                    is_inverse=True,
                )
            )
                .set_global_opts(
                title_opts=opts.TitleOpts(title=test.test_name),
                yaxis_opts=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(formatter="{value} 分"),
                ),
            )
        )
        ranking_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))
                .add_xaxis(['语文', '数学', '英语', '物理', '化学', '生物'])
                .add_yaxis('Ranking', rankings, yaxis_index=1)
                .set_global_opts(title_opts=opts.TitleOpts(test.test_name))
                .set_global_opts(yaxis_opts=opts.AxisOpts(is_inverse=True))

        )
        grade_bar.overlap(ranking_bar)
        tl.add(grade_bar, test.test_time)
    return tl
Beispiel #17
0
def scatter_base(data, mailbox, maxsize) -> Timeline:
    tl = Timeline()
    tl.add_schema(pos_right="10%", pos_left="50%", pos_bottom="87%")
    for i in range(1, 13):
        c = (
            Scatter()
            .add_xaxis(mailbox)
            .add_yaxis("Day", data[i][0])
            .add_yaxis("Night", data[i][1])
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-20)),
                visualmap_opts=opts.VisualMapOpts(type_="size", max_=maxsize, min_=1),
            )
        )
        tl.add(c, "{}月".format(i))    

    return tl
Beispiel #18
0
def _timeline(perf, name=""):
    tl = Timeline(init_opts=opts.InitOpts(width="1000px", height="400px"))
    series = perf.index.get_level_values(0).unique() if isinstance(
        perf.index, pd.MultiIndex) else [name]
    for i, _w in enumerate(series):
        _data = perf.loc[_w] if isinstance(perf.index, pd.MultiIndex) else perf
        n, m = _data.shape
        x, y = np.arange(0, n, 1), np.arange(0, m, 1)
        x, y = np.meshgrid(x, y, indexing='ij')
        z = _data.values.flatten()
        data = list(zip(y.flatten(), x.flatten(), z))
        data = [[int(d[0]), int(d[1]), np.round(d[2], 4)] for d in data]
        h = (HeatMap(
            init_opts=opts.InitOpts(width="1000px", height="300px")).add_xaxis(
                xaxis_data=_data.columns.astype(str).tolist()).add_yaxis(
                    series_name="",
                    yaxis_data=_data.index.astype(str).tolist(),
                    value=data,
                    label_opts=opts.LabelOpts(position='inside', is_show=True),
                ).set_series_opts().set_global_opts(
                    toolbox_opts=opts.ToolboxOpts(is_show=True),
                    legend_opts=opts.LegendOpts(is_show=False),
                    tooltip_opts=opts.TooltipOpts(is_show=True, ),
                    xaxis_opts=opts.AxisOpts(
                        type_="category",
                        splitarea_opts=opts.SplitAreaOpts(
                            is_show=True,
                            areastyle_opts=opts.AreaStyleOpts(opacity=1)),
                    ),
                    yaxis_opts=opts.AxisOpts(
                        type_="category",
                        splitarea_opts=opts.SplitAreaOpts(
                            is_show=True,
                            areastyle_opts=opts.AreaStyleOpts(opacity=1)),
                    ),
                    visualmap_opts=opts.VisualMapOpts(min_=z.min(),
                                                      max_=z.max(),
                                                      is_calculable=True,
                                                      orient="vertical",
                                                      pos_left="left"),
                ))
        tl.add(h, "{}".format(_w))
        if not isinstance(perf.index, pd.MultiIndex):
            tl.add_schema(is_timeline_show=False)
    return tl
Beispiel #19
0
def print_bar(confirm_frame, timelist, all_province_name):
    tl = Timeline(init_opts=opts.InitOpts(
        page_title='疫情可视化', width='1080px', height='480px'))
    # 调节播放速率 ,是否自动播放,是否循环播放,是否显示时间轴
    tl.add_schema(play_interval=300,
                  is_auto_play=True,
                  is_loop_play=False,
                  is_timeline_show=True)
    l = len(timelist)
    for i in range(0, l):
        # 将每天的数据单独拿出来进行排序
        s = {'province': all_province_name, 'confirm': confirm_frame.loc[:][i]}
        s = pd.DataFrame(s)
        # 翻转是镜像翻转所以 这里要从大到小排序
        s = s.sort_values(by='confirm', ascending=1)
        province_name = s[-10:]['province']
        confirm = s[-10:]['confirm']
        heal_list, dead_list = get_Top10info(province_name, l - i)
        bar = Bar()
        bar.add_xaxis(province_name.to_list())
        # 名字,数据,柱状图间距, label标签显示在右侧|这样翻转的时候就在右侧
        # gap 神奇的参数因为每个柱状图有固定位置|宽度l, 正代表向正向移动百分比l,负代表向负向移动百分比l
        bar.add_yaxis('确诊人数',
                      confirm.to_list(),
                      label_opts=opts.LabelOpts(position='right'),
                      color='#696969')
        bar.add_yaxis('治愈人数',
                      heal_list,
                      label_opts=opts.LabelOpts(position='right'),
                      color='#90EE90')
        bar.add_yaxis('死亡人数',
                      dead_list,
                      label_opts=opts.LabelOpts(position='right'),
                      color='#F08080')
        # 设置全局变量:x轴标签倾斜度,html主标题
        bar.set_global_opts(legend_opts=opts.LegendOpts(is_show=True),
                            xaxis_opts=opts.AxisOpts(name_rotate=-15),
                            title_opts=opts.TitleOpts('当前日期:%s' % timelist[i],
                                                      subtitle='数据来自inews'))
        bar.reversal_axis()
        tl.add(bar, timelist[i])
    name = '疫情柱状图.html'
    print(name, '已成功生成到', os.getcwd())
    tl.render(name)
def grid_vertical() -> Grid:
    #grid=Grid()
    #for item in name_list:
    tl = Timeline()
    for t in time_range:
        bar = Bar()
        bar.add_xaxis(name_list[0])
        for name in name_list[0]:
            price_list = list(data[(data['name'] == name)
                                   & (data['dates'] == t)]['price'])
            if len(price_list) == 0:
                bar.add_yaxis(name, [0], category_gap='5%', gap='5%')
            else:
                bar.add_yaxis(name, price_list, category_gap='5%', gap='5%')
        bar.set_global_opts(title_opts=opts.TitleOpts("某商店{}营业额".format(t)))
        tl.add(bar, "{}年".format(t))
        #grid.add(tl, grid_opts=opts.GridOpts(pos_bottom="60%"))
        tl.add_schema(is_auto_play=True, play_interval=1000)
    return tl  #grid
Beispiel #21
0
def plot_timeline():
    """
    Timeline可以将多个图表制作成动画。
    :return:
    """
    # 初始化多组数据
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    year = 5
    start_year = 2018
    num = len(attr)
    # 初始化时间线图形
    timeline = Timeline(init_opts=opts.InitOpts(width='120%', height='300%'))

    # 时间轴添加配置项
    timeline.add_schema(is_auto_play=False,
                        is_loop_play=True,
                        is_timeline_show=True,
                        control_position='right',
                        itemstyle_opts=opts.ItemStyleOpts(color='blue',
                                                          opacity=0.8),
                        play_interval=1000)

    for i in range(5):
        year_sales1 = [randint(10, 100) for _ in range(num)]
        year_sales2 = [randint(200, 500) for _ in range(num)]
        # 初始化
        bar_temp = Bar(init_opts=opts.InitOpts())
        # 加载数据
        bar_temp.add_xaxis(xaxis_data=attr)
        bar_temp.add_yaxis(series_name=f'{start_year+i}年净销售额',
                           y_axis=year_sales1)
        bar_temp.add_yaxis(series_name=f'{start_year+i}年实际销售额',
                           y_axis=year_sales2)
        # bar配置项
        bar_temp.set_global_opts(title_opts=opts.TitleOpts(
            title=f'{start_year + i} 销售额情况'))

        # 时间轮播图添加图形
        timeline.add(bar_temp, f'{start_year + i}年营业额')

    # 输出时间线轮播图
    return timeline.render_embed()
def timeline_map():
    timeline = Timeline(init_opts=opts.InitOpts(page_title="新冠肺炎情况",
                                                width=str(x) + 'px',
                                                height=str(y) + 'px',
                                                theme=ThemeType.DARK))

    for datatemp in pd.date_range(start='2020-03-16',
                                  end=datetime.date.today(),
                                  freq='D'):
        datatemp = str(datatemp).split(" ")[0]
        g = map_visualmap(date=datatemp)
        print(g)
        timeline.add(g, time_point=datatemp)

    timeline.add_schema(
        pos_left='center',
        pos_bottom="50px",
        play_interval=500,
        width=str(x / 1.25) + 'px',
        label_opts=opts.LabelOpts(is_show=True, color="#fff"),
    )
    return timeline
Beispiel #23
0
    def timeline(self):
        time_list = [str(d) for d in self.day]
        timeline = Timeline(init_opts=opts.InitOpts(
            width="1600px", height="900px", theme=self.theme))
        for y in time_list:
            g = self.__get_year_chart(self.data, y)
            timeline.add(g, time_point=str(y[5:]))
        timeline.add_schema(
            orient="vertical",
            is_auto_play=True,
            is_inverse=True,
            play_interval=1000,
            pos_left="null",
            pos_right="5",
            pos_top="20",
            pos_bottom="20",
            width="60",
        )
        save = self.save + ".html"
        print(save)

        timeline.render(save)
def timeline_bmap() -> Timeline:
    tl = Timeline()
    tl.add_schema(pos_left="50%", pos_right="10px", pos_bottom="15px")
    for i in range(2015, 2020):
        bmap = (
            BMap()
            .add_schema(baidu_ak="FAKE_AK", center=[120.13066322374, 30.240018034923])
            .add(
                "bmap",
                [list(z) for z in zip(Faker.provinces, Faker.values())],
                type_="heatmap",
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="Timeline-BMap-热力图-{}年".format(i)),
                visualmap_opts=opts.VisualMapOpts(
                    pos_bottom="center", pos_right="10px"
                ),
                tooltip_opts=opts.TooltipOpts(formatter=None),
            )
        )
        tl.add(bmap, "{}年".format(i))
    return tl
Beispiel #25
0
def render(input_d):
    data, time_list, total_num, maxNum, output_name, title1, title2 = input_d
    minNum = 1
    timeline = Timeline(init_opts=opts.InitOpts(
        width="1520px", height="720px", theme=ThemeType.DARK))
    for y in time_list:
        g = get_year_chart(y, title1, title2)
        timeline.add(g, time_point=str(y))

    timeline.add_schema(
        orient="vertical",
        is_auto_play=True,
        is_inverse=True,
        play_interval=5000,
        pos_left="null",
        pos_right="5",
        pos_top="20",
        pos_bottom="20",
        width="73",
        label_opts=opts.LabelOpts(is_show=True, color="#fff"),
    )
    timeline.render(output_name)
Beispiel #26
0
def generate_timeline_html(time_data):
    tl = Timeline()
    tl.add_schema(is_auto_play=False, play_interval=500, is_loop_play=False)
    for date, bonds in time_data.items():
        _date = datetime.datetime.strftime(date, '%Y-%m-%d')
        x = []
        y = []
        bonds = sorted(bonds.items(), key=lambda i: i[1], reverse=False)
        for name, money, in bonds:
            x.append(name)
            y.append(money)

        bar = (
            Bar(init_opts=opts.InitOpts(
                theme=ThemeType.ROMANTIC)).add_xaxis(x).add_yaxis("价格", y)
            # .add_yaxis("投入资金", y)
            .reversal_axis().set_series_opts(label_opts=opts.LabelOpts(
                is_show=True, position='right'), ).set_global_opts(
                    legend_opts=opts.LegendOpts(is_show=True),
                    title_opts=opts.TitleOpts("{}可转债组合".format(_date)),
                ))
        tl.add(bar, "{}".format(_date))
    return "<center>" + tl.render_embed('template.html', env) + "</center>"
Beispiel #27
0
def draw_time_line():
    time_line = Timeline(init_opts=opts.InitOpts(
        width='1000px', height='600px', theme=ThemeType.DARK))

    for date_i in date_list:
        date_i_chart = get_chart_of_date(date_i)
        time_line.add(date_i_chart, time_point=date_i)

    time_line.add_schema(axis_type="category",
                         orient='horizontal',
                         symbol='arrow',
                         is_auto_play=True,
                         is_inverse=False,
                         play_interval=2000,
                         pos_left='null',
                         pos_right='null',
                         pos_top='null',
                         pos_bottom='10',
                         height='40',
                         label_opts=opts.LabelOpts(is_show=False,
                                                   color='#fff'))

    return time_line
Beispiel #28
0
def timeline_bar_reversal(title="Timeline-Bar-Reversal", is_auto_play=True):
    '''
    动效数据增长图
    '''
    data = getExcelToData1()

    tl = Timeline()
    tl.add_schema(
        is_auto_play=is_auto_play,
        play_interval=100,
        is_loop_play=True,
        is_inverse=False,
        # axis_type='time',
        is_timeline_show=True,  # 是否展示播放按钮
    )

    # for i in range(1950, 2020):
    #     bar = Bar()
    #     bar.add_xaxis(Faker.choose())
    #     bar.add_yaxis("商家A", Faker.values(), label_opts=opts.LabelOpts(position="right"))
    #     bar.add_yaxis("商家B", Faker.values(), label_opts=opts.LabelOpts(position="right"))
    #     bar.reversal_axis()
    #     bar.set_global_opts(title_opts=opts.TitleOpts("{}: {} ".format(title,i)))
    #     tl.add(bar, "{}年".format(i))
    for i in range(1, len(data['date'])):
        bar = Bar()
        bar.add_xaxis(data['kanaal'])
        bar.add_yaxis('新增',
                      data['values'][i - 1],
                      label_opts=opts.LabelOpts(position="right"))
        bar.reversal_axis()
        bar.set_global_opts(
            title_opts=opts.TitleOpts("{}: {} ".format(title, i)))
        tl.add(bar, "{}".format(i))

    return tl
Beispiel #29
0
class TestTimeLine(unittest.TestCase):
    def setUp(self):
        bar0 = (Bar().add_xaxis(["a",
                                 "b"]).add_yaxis("shop a", [1, 2]).add_yaxis(
                                     "shop b", [3, 4]).set_global_opts(
                                         title_opts=opts.TitleOpts("test"),
                                         visualmap_opts=opts.VisualMapOpts()))
        self.tl = Timeline().add(bar0, "year 2015")

    def test_default_label(self):
        eq_(None,
            self.tl.options.get("baseOption").get("timeline").get("label"))

    def test_custom_label(self):
        custom_label_opts = {"custom": "label"}
        self.tl.add_schema(label_opts=custom_label_opts)
        eq_(
            custom_label_opts,
            self.tl.options.get("baseOption").get("timeline").get("label"),
        )

    def test_timeline_vertical(self):
        self.tl.add_schema(orient="vertical")
        eq_("vertical",
            self.tl.options.get("baseOption").get("timeline").get("orient"))

    def test_timeline_inverse(self):
        self.tl.add_schema(is_inverse=True)
        eq_(True,
            self.tl.options.get("baseOption").get("timeline").get("inverse"))

    def test_timeline_width_height(self):
        width, height = "20", "30"
        self.tl.add_schema(width=width, height=height)
        eq_(width,
            self.tl.options.get("baseOption").get("timeline").get("width"))
        eq_(height,
            self.tl.options.get("baseOption").get("timeline").get("height"))

    def test_timeline_visual_map(self):
        eq_(
            type(opts.VisualMapOpts()),
            type(self.tl.options.get("options")[0].get("visualMap")),
        )
class TestTimeLine(unittest.TestCase):
    def setUp(self):
        bar0 = (Bar().add_xaxis(["a",
                                 "b"]).add_yaxis("shop a", [1, 2]).add_yaxis(
                                     "shop b", [3, 4]).set_global_opts(
                                         title_opts=opts.TitleOpts("test"),
                                         visualmap_opts=opts.VisualMapOpts()))
        self.tl = Timeline().add(bar0, "year 2015")

    def test_default_label(self):
        assert_equal(
            None,
            self.tl.options.get("baseOption").get("timeline").get("label"))

    def test_custom_label(self):
        custom_label_opts = {"custom": "label"}
        self.tl.add_schema(label_opts=custom_label_opts)
        assert_equal(
            custom_label_opts,
            self.tl.options.get("baseOption").get("timeline").get("label"),
        )

    def test_timeline_vertical(self):
        self.tl.add_schema(orient="vertical")
        assert_equal(
            "vertical",
            self.tl.options.get("baseOption").get("timeline").get("orient"))

    def test_timeline_inverse(self):
        self.tl.add_schema(is_inverse=True)
        assert_equal(
            True,
            self.tl.options.get("baseOption").get("timeline").get("inverse"))

    def test_timeline_width_height(self):
        width, height = "20", "30"
        self.tl.add_schema(width=width, height=height)
        assert_equal(
            width,
            self.tl.options.get("baseOption").get("timeline").get("width"))
        assert_equal(
            height,
            self.tl.options.get("baseOption").get("timeline").get("height"))

    def test_timeline_visual_map(self):
        assert_equal(
            type(opts.VisualMapOpts()),
            type(self.tl.options.get("options")[0].get("visualMap")),
        )

    def test_timeline_graphic(self):
        self.tl.add_schema(graphic_opts=[
            opts.GraphicGroup(
                graphic_item=opts.GraphicItem(
                    rotation=JsCode("Math.PI / 4"),
                    bounding="raw",
                    right=110,
                    bottom=110,
                    z=100,
                ),
                children=[
                    opts.GraphicRect(
                        graphic_item=opts.GraphicItem(
                            left="center", top="center", z=100),
                        graphic_shape_opts=opts.GraphicShapeOpts(width=400,
                                                                 height=50),
                        graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                            fill="rgba(0,0,0,0.3)"),
                    ),
                    opts.GraphicText(
                        graphic_item=opts.GraphicItem(
                            left="center", top="center", z=100),
                        graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                            text="pyecharts bar chart",
                            font="bold 26px Microsoft YaHei",
                            graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                                fill="#fff"),
                        ),
                    ),
                ],
            )
        ])
        assert_equal(
            type(opts.GraphicGroup()),
            type(
                self.tl.options.get("baseOption").get("timeline").get(
                    "graphic")[0]),
        )