Exemplo n.º 1
0
def test_page_render_embed():
    bar = _create_bar()
    line = _create_line()
    content = Page().add(bar, line).render_embed()
    assert_true(len(content) > 8000)
Exemplo n.º 2
0
def page_layout2() -> Page:
    page = Page(layout=Page.SimplePageLayout)
    page.add(level_distribution_bar(), level_distribution_pie())
    return page
Exemplo n.º 3
0
def analys_of_data(datas):
    """
    对主播类型进行分类,统计
    (dict)type_dict : {
        'type' : {
            'count': int,
            'popularity': int,
        }
        'type' : str(popularity*10000 + count)
    }
    """
    type_dict = dict()
    for data in datas:
        if data['type'] not in type_dict.keys():
            type_dict[data['type']] = data['popularity'] * 100000 + 1
        else:
            type_dict[data['type']] += data['popularity'] * 100000 + 1

    num_list = sorted([num%100000 for num in list(type_dict.values())], reverse=True)     # 获得类型数量的降序列表
    popul_list = sorted([int(num/100000) for num in list(type_dict.values())], reverse=True)     # 获得类型人气值的降序列表
    # 人气前25名的直播内容统计
    data_list = sorted(datas, key=lambda x: x['popularity'], reverse=True)
    popul_dict = dict()
    for data in data_list[:25]:
        if data['type'] not in popul_dict.keys():
            popul_dict[data['type']] = data['popularity'] * 100 + 1
        else:
            popul_dict[data['type']] += data['popularity'] * 100 + 1

    # 创建统计前25位人气主播的网页
    page_1 = Page(page_title='关于前25位人气主播分析')
    a = (
        Bar(init_opts=opts.InitOpts(width='100%'))
        .add_xaxis([data_list[num]['name'] for num in range(25)])
        .add_yaxis('',[round(data_list[num]['popularity']/10000,1) for num in range(25)], color='#fa0000')
        .set_global_opts(
            title_opts=opts.TitleOpts(title="前25位人气主播排名\n(单位:万)"),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
        )
        .set_series_opts(
            xaxis_opts=opts.AxisOpts(name='主播名称'),
            title_opts=opts.TitleOpts(title="人气值占比",pos_left='10%',pos_top='2%'),
            legend_opts=opts.LegendOpts(is_show=False),
        )
    )
    b = (
        Pie(init_opts=opts.InitOpts(width='100%'))
        .add(
            series_name="数量占比",
            data_pair=[(list(popul_dict.keys())[num],list(popul_dict.values())[num]%100) for num in range(popul_dict.__len__())],
            radius=50,
            center=['90%','15%'],
        )
        .add(
            series_name="人气占比",
            data_pair=[(list(popul_dict.keys())[num],int(list(popul_dict.values())[num]/100)) for num in range(popul_dict.__len__())],
            radius=50,
            center=['90%','40%'],
        )
        .set_series_opts(
            title_opts=opts.TitleOpts(title='数量占比情况'),
            legend_opts=opts.LegendOpts(type_='scroll',pos_left="50%", pos_top="2%",is_show=True),
        )
    )
    grid = (
        Grid(init_opts=opts.InitOpts(width='100%',height='720px',theme=ThemeType.DARK))
        .add(a, grid_opts=opts.GridOpts(pos_top="10%", pos_right="10%"))
        .add(b, grid_opts=opts.GridOpts(pos_left="90%", pos_top='10%'))
    )
    page_1.add(grid)
    page_1.render(f'{data_path}/analys_of_25.html')
    # 提取类型前32(数量)的进行分类
    source_num_1 = list()
    source_num_2 = list()
    source_num_3 = list()
    source_num_4 = list()
    source_num_1.append(["数量", "人气", "类型"])
    source_num_2.append(["数量", "人气", "类型"])
    source_num_3.append(["数量", "人气", "类型"])
    source_num_4.append(["数量", "人气", "类型"])
    for num in range(type_dict.__len__()):
        type_num = list(type_dict.values())[num]%100000
        type_popul = int(list(type_dict.values())[num]/100000)
        type_name = list(type_dict.keys())[num]
        if num_list[8] < type_num <= num_list[0]:
            source_num_1.append([type_num, type_popul, type_name])
        elif num_list[16] < type_num <= num_list[8]:
            source_num_2.append([type_num, type_popul, type_name])
        elif num_list[24] < type_num <= num_list[16]:
            source_num_3.append([type_num, type_popul, type_name])
        elif num_list[32] < type_num <= num_list[24]:
            source_num_4.append([type_num, type_popul, type_name])

    # 提取类型前32(人气)的进行分类
    source_popul_1 = list()
    source_popul_2 = list()
    source_popul_3 = list()
    source_popul_4 = list()
    source_popul_other = {
        'type': '其他',
        'popularity': 0,
        'num': 0,
    }
    source_popul_1.append(["人气", "数量", "类型"])
    source_popul_2.append(["人气", "数量", "类型"])
    source_popul_3.append(["人气", "数量", "类型"])
    source_popul_4.append(["人气", "数量", "类型"])
    for num in range(type_dict.__len__()):
        type_num = list(type_dict.values())[num]%100000
        type_popul = int(list(type_dict.values())[num]/100000)
        type_name = list(type_dict.keys())[num]
        if popul_list[8] < type_popul <= popul_list[0]:
            source_popul_1.append([type_popul, type_num, type_name])
        elif popul_list[16] < type_popul <= popul_list[8]:
            source_popul_2.append([type_popul, type_num, type_name])
        elif popul_list[24] < type_popul <= popul_list[16]:
            source_popul_3.append([type_popul, type_num, type_name])
        elif popul_list[32] < type_popul <= popul_list[24]:
            source_popul_4.append([type_popul, type_num, type_name])
        else:
            source_popul_other['popularity'] += type_popul
            source_popul_other['num'] += type_num
    # # 创建一个网页实例,用于整合多张图表
    page_2 = Page(page_title='直播类型一览图1')
    page_3 = Page(page_title='直播类型一览图2')

    # 创建横向柱状图
    def create_bar(source,page,x_type,x_name,y_type,title,range,range_text,split_num=8):
        c = (
            Bar(init_opts=opts.InitOpts(width='100%',height='480px',theme=ThemeType.DARK))
            .add_dataset(source=source)
            .add_yaxis(
                series_name="",
                y_axis=[],
                encode={"x": x_type, "y": y_type},
                label_opts=opts.LabelOpts(is_show=False),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title=title),
                xaxis_opts=opts.AxisOpts(name=x_name),
                yaxis_opts=opts.AxisOpts(type_="category"),
                visualmap_opts=opts.VisualMapOpts(
                    orient="horizontal",
                    pos_left="center",
                    min_=range[0],
                    max_=range[1],
                    range_text=range_text,
                    dimension=0,
                    range_color=["#D7DA8B", "#E15457"],
                    is_piecewise=True,
                    split_number=split_num,
                ),
            )
        )
        page.add(c)

    create_bar(source_num_1,page_2,'人气','人气','类型','类型人气(数量:前8名)',(num_list[7],num_list[0]),('数量高','数量低'))
    create_bar(source_num_2,page_2,'人气','人气','类型','类型人气(数量:第8~16名)',(num_list[15],num_list[8]),('数量高','数量低'))
    create_bar(source_num_3,page_2,'人气','人气','类型','类型人气(数量:第16~24名)',(num_list[23],num_list[16]),('数量高','数量低'))
    create_bar(source_num_4,page_2,'人气','人气','类型','类型人气(数量:第24~32名)',(num_list[31],num_list[24]),('数量高','数量低'))
    page_2.render(f'{data_path}/type_of_num.html')

    create_bar(source_popul_1,page_3,'数量','数量','类型','类型数量(人气:前8名)',(popul_list[7],popul_list[0]),('人气高','人气低'),split_num=5)
    create_bar(source_popul_2,page_3,'数量','数量','类型','类型数量(人气:第8~16名)',(popul_list[15],popul_list[8]),('人气高','人气低'),split_num=5)
    create_bar(source_popul_3,page_3,'数量','数量','类型','类型数量(人气:第16~24名)',(popul_list[23],popul_list[16]),('人气高','人气低'),split_num=5)
    create_bar(source_popul_4,page_3,'数量','数量','类型','类型数量(人气:第24~32名)',(popul_list[31],popul_list[24]),('人气高','人气低'),split_num=5)
    page_3.render(f'{data_path}/type_of_popular.html')

    # 类型平均人气一览图
    source = list()
    for s in source_popul_1[1:]:
        source.append([s[2],round(s[0]/s[1]/100000,1)])
    for s in source_popul_2[1:]:
        source.append([s[2],round(s[0]/s[1]/100000,1)])
    for s in source_popul_3[1:]:
        source.append([s[2],round(s[0]/s[1]/100000,1)])
    source.append([source_popul_other['type'],round(source_popul_other['popularity']/100000/source_popul_other['num'],1)])
    d = (
        Bar(init_opts=opts.InitOpts(width='100%',height='720px',theme=ThemeType.DARK,page_title='直播平均人气排名'))
        .add_xaxis([s[0] for s in source])
        .add_yaxis('人气值(单位:万)',[s[1] for s in source], color='#fa0000')
        .set_global_opts(
            title_opts=opts.TitleOpts(title="直播类型平均人气排名"),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
        )
        .set_series_opts(
            xaxis_opts=opts.AxisOpts(name='直播类型'),
            legend_opts=opts.LegendOpts(is_show=False),
        )
        .render(f'{data_path}/avg_of_popular.html')
    )
Exemplo n.º 4
0
            is_scale=True,
            split_number=2,
            axislabel_opts=opts.LabelOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_show=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    ))

    # Kline And Line
    overlap_kline_line = kline.overlap(line)

    # Grid Overlap + Bar
    grid_chart = Grid()
    grid_chart.add(
        overlap_kline_line,
        grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", height="50%"),
    )
    grid_chart.add(
        bar,
        grid_opts=opts.GridOpts(pos_left="10%",
                                pos_right="8%",
                                pos_top="70%",
                                height="16%"),
    )
    return grid_chart


Page().add(*[fn() for fn, _ in C.charts]).render('grid_example.html')
Exemplo n.º 5
0
for i in range(len(tracelist)):
    tracelistthree = tracelist[i][1:4]
    if tracelistthree not in newtracelist:
        newtracelist.append(tracelistthree)

for j in range(len(newtracelist)):
    for i in range(len(tracelist)):
        if newtracelist[j][0]==tracelist[i][1] and newtracelist[j][1]==tracelist[i][2] and newtracelist[j][2]==tracelist[i][3]:
            newtracelist[j].append(tracelist[i][0])
            break


verden = list(set(verden))
horden = list(set(horden))
newtracelist.insert(0,firstPoint)
newtracelist.append(endPoint)

print(len(newtracelist))
print(newtracelist)
print(horden)
print(verden)

print(newtracelist)
page = Page()# st
data = newtracelist
range_color = ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf',
               '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
scatter3D = Scatter3D() #设置图表的高和宽
scatter3D.add("", data,True, range_color) #视觉映射和颜色选择
page.add(scatter3D)
page.render()
Exemplo n.º 6
0
from pyecharts import options as opts
from pyecharts.charts import Bar, Grid, Line, Liquid, Page, Pie


def pie_echart():
    keys = ['男性', '女性']
    values = [7322452, 7438028]
    data = zip(keys, values)
    c = Pie()
    c.add("饼状图", list(data))
    c.set_global_opts(title_opts=opts.TitleOpts(title='男女比例情况'))
    return c


def bar_echart():
    c = Bar()
    c.add_xaxis(['1978年', '1980年', '1990年', '2000年', '2017年', '2018年'])
    c.add_yaxis("人均GDP", [449, 565, 2123, 11471, 98011, 105399])
    c.add_yaxis("居民储蓄存款余额", [30, 52, 866, 8240, 84474, 90273])
    return c


if __name__ == '__main__':
    page = Page()
    page.add(pie_echart(), bar_echart(), pie_echart(), bar_echart())
    page.render("all.html")
Exemplo n.º 7
0
    page.add(cloud)


#判断变量类型的函数
def typeof(variate):
    type = None
    if isinstance(variate, int):
        type = "int"
    elif isinstance(variate, str):
        type = "str"
    elif isinstance(variate, float):
        type = "float"
    elif isinstance(variate, list):
        type = "list"
    elif isinstance(variate, tuple):
        type = "tuple"
    elif isinstance(variate, dict):
        type = "dict"
    elif isinstance(variate, set):
        type = "set"
    return type


if __name__ == '__main__':
    name = sys.argv[1]
    page = Page()
    getyear(name)
    getcloud()
    #年度表格添加
    page.render(r'views/process.handlebars')
Exemplo n.º 8
0
def china_citys_history():

    page1 = Page()
    dwf.createFile(savaPath+'/中国各省的城市历史疫情信息')
    path = readPath + '中国各省的城市历史疫情信息'
    floder = glob.glob(os.path.join(path, "*"))


    # 判断数据是否存在
    def checknan(name):
        if np.any(pd.isnull(name)) == True:
            name.fillna(value="0", inplace=True)

    for name in floder:
        for root, dirs, files in os.walk(name, topdown=False):

            for filename in files:
                name = ''.join('%s' % id for id in name)
                # print(type(filename))
                # print(type(name))
                filepath = name + '/' + filename
                filepath = filepath.replace('\\','/')
                data = pd.read_excel(filepath, index=False)
                province_name = re.findall('([\u4e00-\u9fa5]*)\\\\[\u4e00-\u9fa5]*\.xlsx', filepath)
                province_name = ''.join('%s' % id for id in province_name)
                city_name = re.findall('([\u4e00-\u9fa5]*)\.xlsx', filepath)
                city_name = ''.join('%s' % id for id in city_name)
                # print(province_name+'and'+city_name)
                checknan(data['confirm'])
                checknan(data['confirm_add'])
                checknan(data['heal'])
                checknan(data['dead'])

                y1_confirm = data['confirm']
                y1_confirm = list(y1_confirm)
                y1_confirm = [int(i) for i in y1_confirm]

                y2_confirm_add = data['confirm_add']
                y2_confirm_add = list(y2_confirm_add)
                y2_confirm_add = [int(i) for i in y2_confirm_add]

                y3_heal = data['heal']
                y3_heal = list(y3_heal)
                y3_heal = [int(i) for i in y3_heal]

                y4_dead = data['dead']
                y4_dead = list(y4_dead)
                y4_dead = [int(i) for i in y4_dead]

                date_list = []
                for j in data['date']:
                    date_list.append(j)

                x = date_list

                lines = (
                    Line()
                        .add_xaxis(xaxis_data=x)
                        .add_yaxis(series_name='确诊人数', y_axis=y1_confirm, is_symbol_show=True,
                                   label_opts=opts.LabelOpts(is_show=False),
                                   markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                        .add_yaxis(series_name='增加确诊人数', y_axis=y2_confirm_add, is_symbol_show=True,
                                   label_opts=opts.LabelOpts(is_show=False),
                                   markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                        .add_yaxis(series_name='治愈人数', y_axis=y3_heal, is_symbol_show=True,
                                   label_opts=opts.LabelOpts(is_show=False),
                                   markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                        .add_yaxis(series_name='死亡人数', y_axis=y4_dead, is_symbol_show=True,
                                   label_opts=opts.LabelOpts(is_show=False),
                                   markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                        .set_global_opts(
                        title_opts=opts.TitleOpts(title="%s" % (city_name) + "疫情走势", subtitle="数据来源:腾讯新闻"),
                        yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=10, interval=3)))
                )

                name1 = name.replace('data/中国各省的城市历史疫情信息\\', 'data/data_DaliyChangeView/中国各省的城市历史疫情信息/')
                dwf.createFile(name1)

                save_path = name1 + '%s.txt'

                # lines.render(save_path % (city_name), index=False)
                page1.add(lines)  # 将图像加入同一页
                if flag:
                    dwf.write_to_file(save_path % (city_name),
                                      str(lines.dump_options_with_quotes()))
            page.render(savaPath + '/中国各省的城市历史疫情信息/analyse_all.html')
Exemplo n.º 9
0
def foregin_city_all():
    path = readPath + '/各国各地区疫情信息'

    path2 = savaPath + '/各国疫情严重程度排名前十地区信息'
    dwf.createFile(path2)

    Filelist = []  # 将当前文件夹内的所有表名存放此列表
    for home, dirs, files in os.walk(path):
        for filename in files:
            Filelist.append(filename)

    # 判断数据是否存在
    def checknan(name):
        if np.any(pd.isnull(name)) == True:
            name.fillna(value="0", inplace=True)

    # 随机颜色生成用于制作南丁格尔玫瑰图
    def randomcolor(kind):

        colors = []
        for i in range(kind):
            colArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
            color = ""
            for i in range(6):
                color += colArr[random.randint(0, 14)]
            colors.append("#" + color)
        return colors

    for i in Filelist:
        page1 = Page()
        data = pd.read_excel(readPath + '/各国各地区疫情信息/%s' % (i), index=False)
        data_sort = data.sort_values(axis=0, ascending=False, by=['confirm'])
        data_message = data_sort.head(10)  # 提取疫情严重程度排名前十地区的信息
        n = i[:-5]  # 只提取国家名,不要后缀(.xlsx)

        checknan(data_message['confirm'])
        checknan(data_message['heal'])
        checknan(data_message['dead'])

        y1_confirm = data_message['confirm']
        y1_confirm = list(y1_confirm)
        y1_confirm = [int(i) for i in y1_confirm]

        y2_dead = data_message['dead']
        y2_dead = list(y2_dead)
        y2_dead = [int(i) for i in y2_dead]

        y3_heal = data_message['heal']
        y3_heal = list(y3_heal)
        y3_heal = [int(i) for i in y3_heal]

        name_list = []
        for j in data_message['name']:
            name_list.append(j)

        x = name_list
        color_series = randomcolor(len(x))
        # Bars = (
        #     Bar(init_opts=opts.InitOpts(width='1080px',height='700px'))
        #         .add_xaxis(xaxis_data=x)
        #         .add_yaxis(series_name='确诊人数', yaxis_data=y1_confirm)
        # )


        #####画南丁格尔玫瑰图##########
        # 画出确诊人数的图
        fig = Pie(init_opts=opts.InitOpts(width='500px', height='700px'))
        fig.add("", [list(z) for z in zip(x, y1_confirm)],
                radius=['30%', '135%'],
                center=['50%', '65%'],
                rosetype='area')
        fig.set_global_opts(title_opts=opts.TitleOpts(title=n + '疫情严重程度排名前十地区的确诊人数'),
                            legend_opts=opts.LegendOpts(is_show=False))
        fig.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='inside', font_size=12,
                                                      formatter='{b}:{c}例', font_style='italic', font_weight='bold',
                                                      font_family='Microsoft YaHei'))  # b:province;c:num
        fig.set_colors(color_series)
        # 画出死亡人数的图
        fig1 = Pie(init_opts=opts.InitOpts(width='500px', height='700px'))
        fig1.add("", [list(z) for z in zip(x, y2_dead)],
                 radius=['30%', '135%'],
                 center=['50%', '65%'],
                 rosetype='area')
        fig1.set_global_opts(title_opts=opts.TitleOpts(title=n + '疫情严重程度排名前十地区的死亡人数'),
                             legend_opts=opts.LegendOpts(is_show=False))
        fig1.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='inside', font_size=12,
                                                       formatter='{b}:{c}例', font_style='italic', font_weight='bold',
                                                       font_family='Microsoft YaHei'))  # b:province;c:num
        # 画出治愈人数的图
        fig2 = Pie(init_opts=opts.InitOpts(width='500px', height='700px'))
        fig2.add("", [list(z) for z in zip(x, y3_heal)],
                 radius=['30%', '135%'],
                 center=['50%', '65%'],
                 rosetype='area')
        fig2.set_global_opts(title_opts=opts.TitleOpts(title=n + '疫情严重程度排名前十地区的治愈人数'),
                             legend_opts=opts.LegendOpts(is_show=False))
        fig2.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='inside', font_size=12,
                                                       formatter='{b}:{c}例', font_style='italic', font_weight='bold',
                                                       font_family='Microsoft YaHei'))  # b:province;c:num
        page1.add(fig)  # 将图像加入同一页
        page1.add(fig1)  # 将图像加入同一页
        page1.add(fig2)  # 将图像加入同一页
        page1.render(savaPath + '/各国疫情严重程度排名前十地区信息/%s.html' % (n), index=False)
        if flag:
            dwf.write_to_file(savaPath + '/各国疫情严重程度排名前十地区信息/(确诊)%s.txt' % (n),str(fig.dump_options_with_quotes()))
            dwf.write_to_file(savaPath + '/各国疫情严重程度排名前十地区信息/(死亡)%s.txt' % (n),str(fig1.dump_options_with_quotes()))
            dwf.write_to_file(savaPath + '/各国疫情严重程度排名前十地区信息/(治愈)%s.txt' % (n),str(fig2.dump_options_with_quotes()))
Exemplo n.º 10
0
            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)


page = Page(layout=Page.SimplePageLayout)
# 需要自行调整每个 chart 的 height/width,显示效果在不同的显示器上可能不同
page.add(line_markpoint(), line_markpoint1())
page.render("test.html")
Exemplo n.º 11
0
import pandas as pd
import numpy as np
import os,glob,re,random
from pyecharts.charts import Line,Bar,Pie#折线图绘制所需要的库
import pyecharts.options as opts#设置全局变量

from pyecharts.charts import Page#将所有图像放在同一页所需要的库
from util import dealWithFile as dwf

readPath = dwf.rootPath #读取数据的地方
savaPath = dwf.saveDaliyChangeView #生成结果的地方
flag = dwf.flag #是否生成数据


page=Page()#创建一个分页用于放所有的图像在这一分页上
##################中国历史疫情总体信息##############
def china_history_all():

    China_all = pd.DataFrame(pd.read_excel(readPath+'/中国总体历史疫情信息/历史总体信息.xlsx'))  # 读取信息
    CNday_date = list(China_all['date'])
    CNday_confirm = list(China_all['confirm'])
    CNday_dead = list(China_all['dead'])
    CNday_heal = list(China_all['heal'])
    line_CNday = (
        Line()
            .add_xaxis(xaxis_data=CNday_date)  # xaxis_data为x轴,y_axis为y轴
            .add_yaxis(series_name='确诊', y_axis=CNday_confirm, label_opts=opts.LabelOpts(is_show=False))
            .add_yaxis(series_name='死亡', y_axis=CNday_dead, label_opts=opts.LabelOpts(is_show=False))
            .add_yaxis(series_name='治愈', y_axis=CNday_heal, label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(title_opts=opts.TitleOpts(title='中国疫情历史总体信息', pos_left='50%', pos_top='10%'),
                             tooltip_opts=opts.TooltipOpts(axis_pointer_type='cross'))
Exemplo n.º 12
0
from pyecharts.charts import Bar, Line, Grid, Page
from pyecharts import options as opts
from pyecharts.faker import Faker
x = Faker.choose()
y = Faker.values()

bar = (Bar().add_xaxis(x).add_yaxis("销量", y))

line = (Line().add_xaxis(x).add_yaxis("销量", y))
#grid,并行多图,它可以使得多个图表并行的排成一排
# grid = (
#     #设置页面的宽度
#     Grid(init_opts=opts.InitOpts(width='1200px'))
#     #GridOpts就是为grid布局而生的一个配置项,常用的几个参数pos_top,pos_bottom,pos_left,pos_right
#     .add(bar,grid_opts=opts.GridOpts(is_show=True,pos_top="50%",background_color='red',border_color='black'))
#     .add(line,grid_opts=opts.GridOpts(is_show=True,pos_bottom='50%',border_color='blue'))
#     .render()
# )
#page 顺序多图,有3种布局管理器:默认,SimplePageLayout,GraggablePageLayout
page = (
    #布局管理器会自动寻找最佳的布局方案并给与适当的间隔
    # Page(layout=Page.SimplePageLayout)
    #布局管理器可以拖拽
    Page(layout=Page.DraggablePageLayout).add(bar, line).render())
Exemplo n.º 13
0
    def show_factor(self,
                    name,
                    value,
                    file_html,
                    freq="30分钟",
                    open_in_browser=True):
        """查看因子某个值的结果

        :param freq:
        :param name: str
            因子名
        :param value: any
            因子值
        :param file_html: str
        :param open_in_browser: bool
        :return:
        """
        freq_m = {"1分钟": 1, "5分钟": 5, "30分钟": 30}
        rows = [x for x in self.factors if x[name] == value]
        value1 = [{
            "x": s['dt'],
            "y": k,
            "heat": v
        } for s in rows for k, v in s.items() if "百分位" in k]
        value2 = [{
            "x": s['dt'],
            "y": k,
            "heat": v
        } for s in rows for k, v in s.items() if "均收益" in k]
        x_label = [s['dt'] for s in rows]
        y_label1 = [k for k, _ in rows[0].items() if "百分位" in k]
        y_label2 = [k for k, _ in rows[0].items() if "均收益" in k]

        hm1 = heat_map(value1,
                       x_label=x_label,
                       y_label=y_label1,
                       title="{}历史表现评估(N周期区间百分位)".format(name),
                       width="1400px",
                       height="480px")
        hm2 = heat_map(value2,
                       x_label=x_label,
                       y_label=y_label2,
                       title="{}历史表现评估(N周期区间收益)".format(name),
                       width="1400px",
                       height="480px")

        bs = [{
            "dt": bar_end_time(s['dt'], m=freq_m[freq]),
            "mark": "buy",
            "price": round(s['close'], 2)
        } for s in rows]
        chart_kline = self.show_bs(bs,
                                   freq=freq,
                                   width="1400px",
                                   height='480px')
        page = Page(layout=Page.DraggablePageLayout,
                    page_title="{}".format(name))
        page.add(hm1, hm2, chart_kline)

        if file_html:
            page.render(file_html)
            if open_in_browser:
                webbrowser.open(file_html)
        return page
Exemplo n.º 14
0
def test_page_render_notebook():
    page = Page()
    page.add(_create_line(), _create_bar(), _create_table())
    html = page.render_notebook().__html__()
    assert_in("City name", html)
Exemplo n.º 15
0
def get_all_chart():
    page = Page()
    page.add(get_language_proportion())
    page.add(get_salary_proportion())
    page.add(get_map())
    #
    page.add(get_education_background())
    page.render("temp/all.html")
    # get_education_background()

    pass
Exemplo n.º 16
0
def china_provinces_history():

    page1 = Page()

    path2 = savaPath + '/中国各省市历史疫情信息'
    dwf.createFile(path2)

    path = readPath + '/中国各省市历史疫情信息'
    Filelist = []
    for home, dirs, files in os.walk(path):
        for filename in files:
            Filelist.append(filename)

    # print(Filelist)
    def checknan(name):
        if np.any(pd.isnull(name)) == True:
            name.fillna(value="0", inplace=True)

    for i in Filelist:
        data = pd.read_excel(readPath + '/中国各省市历史疫情信息/%s' % (i), index=False)
        n = i[:-5]

        checknan(data['confirm'])
        checknan(data['confirm_add'])
        checknan(data['heal'])
        checknan(data['dead'])

        y1_confirm = data['confirm']
        y1_confirm = list(y1_confirm)
        y1_confirm = [int(i) for i in y1_confirm]

        y2_confirm_add = data['confirm_add']
        y2_confirm_add = list(y2_confirm_add)
        y2_confirm_add = [int(i) for i in y2_confirm_add]

        y3_heal = data['heal']
        y3_heal = list(y3_heal)
        y3_heal = [int(i) for i in y3_heal]

        y4_dead = data['dead']
        y4_dead = list(y4_dead)
        y4_dead = [int(i) for i in y4_dead]

        date_list = []
        for j in data['date']:
            date_list.append(j)

        x = date_list

        linse12 = (
            Line()
                .add_xaxis(xaxis_data=x)
                .add_yaxis(series_name='确诊人数', y_axis=y1_confirm, is_symbol_show=True,
                           label_opts=opts.LabelOpts(is_show=False),
                           markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                .add_yaxis(series_name='增加确诊人数', y_axis=y2_confirm_add, is_symbol_show=True,
                           label_opts=opts.LabelOpts(is_show=False),
                           markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                .add_yaxis(series_name='治愈人数', y_axis=y3_heal, is_symbol_show=True,
                           label_opts=opts.LabelOpts(is_show=False),
                           markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                .add_yaxis(series_name='死亡人数', y_axis=y4_dead, is_symbol_show=True,
                           label_opts=opts.LabelOpts(is_show=False),

                           markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max"), ]))
                .set_global_opts(title_opts=opts.TitleOpts(title="%s" % (n) + "疫情走势", subtitle="数据来源:腾讯新闻"),
                                 yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=10, interval=3)))
        )

        # lines.render(savaPath + '\\daliy_changes_view\\中国各省市历史疫情信息\\%s.html' % (n), index=False)
        page1.add(linse12)  # 将图像加入同一页
        if flag:
            dwf.write_to_file(savaPath + '/中国各省市历史疫情信息/%s.txt' % (n), str(linse12.dump_options_with_quotes()))
    page.render(savaPath + '/中国各省市历史疫情信息/analyse_all.html')
Exemplo n.º 17
0
def plot_covid_19_world_situation(world_data):
    """
    绘制全球新冠疫情情况:
        1. 包含新增确诊人数
        2. 新增死亡人数
        3. 累计确诊人数
        4. 累计死亡人数
        5. 累计检测人数
        6. 全病例比例
    Args:
        world_data:pd.DataFrame
            全球数据
    Returns:html
            绘制成html
    """
    last_date = max(world_data['Date'])

    # 1.全球单日新增确诊病例
    now_date_confirmed_info = world_data[[
        'Difference', 'Country_Region'
    ]][(world_data[world_data.columns[0]] == 'Confirmed')
       & (world_data['Date'] == last_date)]
    now_date_confirmed_info = now_date_confirmed_info.groupby(
        ['Country_Region']).agg({
            'Difference': 'sum'
        }).reset_index()

    # 2.全球单日新增死亡病例
    now_date_deaths_info = world_data[[
        'Difference', 'Country_Region'
    ]][(world_data[world_data.columns[0]] == 'Deaths')
       & (world_data['Date'] == last_date)]
    now_date_deaths_info = now_date_deaths_info.groupby(['Country_Region'
                                                         ]).agg({
                                                             'Difference':
                                                             'sum'
                                                         }).reset_index()

    # 3.全球总共确诊病例
    total_confirmed_info = world_data[[
        'Difference', 'Country_Region'
    ]][world_data[world_data.columns[0]] == 'Confirmed']
    total_confirmed_info = total_confirmed_info.groupby(['Country_Region'
                                                         ]).agg({
                                                             'Difference':
                                                             'sum'
                                                         }).reset_index()

    # 4.全球总共死亡病例
    total_deaths_info = world_data[[
        'Difference', 'Country_Region'
    ]][world_data[world_data.columns[0]] == 'Deaths']
    total_deaths_info = total_deaths_info.groupby(['Country_Region']).agg({
        'Difference':
        'sum'
    }).reset_index()

    # 四种指标字典
    # express_dict = {
    #     'day_confirmed':
    #         {
    #             'data': now_date_confirmed_info,
    #             'case_type': 'confirmed',
    #             'date_type': 'day',
    #         },
    #     'day_deaths':
    #         {
    #             'data': now_date_deaths_info,
    #             'case_type': 'deaths',
    #             'date_type': 'day',
    #         },
    #     'total_confirmed':
    #         {
    #             'data': total_confirmed_info,
    #             'case_type': 'confirmed',
    #             'date_type': 'total',
    #         },
    #     'total_deaths':
    #         {
    #             'data': total_deaths_info,
    #             'case_type': 'deaths',
    #             'date_type': 'total',
    #         },
    # }

    express_dict = {
        'total_confirmed': {
            'data': total_confirmed_info,
            'case_type': 'confirmed',
            'date_type': 'total',
        },
    }

    for name, info in express_dict.items():
        data = info['data']
        max_num = max(data['Difference'])
        total_num = sum(data['Difference'])
        data_pair = [(country, int(confirmed_num)) for country, confirmed_num
                     in zip(data['Country_Region'], data['Difference'])]
        express_dict[name]['max_num'] = max_num
        express_dict[name]['total_num'] = total_num
        express_dict[name]['data_pair'] = data_pair

    # 初始化pages
    pages = Page(page_title=f'全球{last_date}情况', layout=opts.PageLayoutOpts())

    # 绘制地图
    for plot_name, plot_data in express_dict.items():
        # 初始化地图
        map = Map(init_opts=opts.InitOpts(
            width='1000px', height='800px', bg_color="#000f1a"))

        # 加载数据:其中maptype可以初始化地图类型,而geo中需要单独设置
        if plot_data['case_type'] == 'confirmed':
            case_name = '确诊'
        else:
            case_name = '死亡'
        if plot_data['date_type'] == 'day':
            date_type = '当日'
        else:
            date_type = '累计'
        map.add(
            series_name=f'全球{last_date}{date_type}{case_name}人数分布',
            data_pair=plot_data['data_pair'],
            maptype='world',
            label_opts=opts.LabelOpts(is_show=True, color='white'),
            # itemstyle_opts是设置每个项目中标注点的样式 area_color是设置项目的背景色,color是设置项目的点的颜色
            itemstyle_opts=opts.ItemStyleOpts(area_color='#2a2a28',
                                              color="#d3d307"))

        # 配置
        map.set_global_opts(
            title_opts=opts.TitleOpts(
                title=f'全球{last_date}{date_type}{case_name}人数分布',
                subtitle=f"全球新增确诊:{plot_data['total_num']}"),
            # # 视觉配置
            # visualmap_opts=opts.VisualMapOpts(
            #     type_='color',
            #     min_=0,
            #     max_=plot_data['max_num'],
            # ),
            # tooltip_opts=opts.TooltipOpts(is_show=True)
            # 图形配置
        )

        # 添加图形系列
        pages.add(map)
    """
    # 绘制美国和中国每日新增确诊病例趋势线
    us_day_confirmed_data = world_data[
        (world_data['Country_Region'] == 'United States') & (world_data['Case_Type'] == 'Confirmed')]
    us_day_confirmed_grouped = us_day_confirmed_data[['Date', 'Difference']].groupby(['Date']).agg(
        {'Difference': 'sum'}).reset_index()
    gc.collect()
    us_day_confirmed_grouped_x = pd.to_datetime(us_day_confirmed_grouped['Date'], dayfirst=False)
    us_day_confirmed_grouped_x = list(us_day_confirmed_grouped_x.apply(lambda x: x.date()))
    us_day_confirmed_grouped_dict = {date: confirmed for date, confirmed in
                                     zip(us_day_confirmed_grouped_x, list(us_day_confirmed_grouped['Difference']))}
    us_day_confirmed_grouped_x = sorted(us_day_confirmed_grouped_x)
    us_day_confirmed_grouped_y = [us_day_confirmed_grouped_dict[date] for date in us_day_confirmed_grouped_x]
    total_confirmed_num = sum(us_day_confirmed_grouped_y)
    # 绘制折线图
    line = Line(init_opts=opts.InitOpts())

    # 添加X,Y数据
    line.add_xaxis(xaxis_data=us_day_confirmed_grouped_x)
    line.add_yaxis(series_name='美国确诊病例趋势', y_axis=us_day_confirmed_grouped_y)

    # 添加折线图配置
    line.set_global_opts(title_opts=opts.TitleOpts(title='美国新增确诊病例趋势', subtitle=f'美国累计确诊病例{total_confirmed_num}'))

    pages.add(line)

    # 绘制美国累计确诊病例
    us_add_confirmed_grouped = us_day_confirmed_data[['Date', 'Cases']].groupby(['Date']).agg(
        {'Cases': 'sum'}).reset_index()
    us_add_confirmed_grouped_x = pd.to_datetime(us_add_confirmed_grouped['Date'], dayfirst=False)
    us_add_confirmed_grouped_x = list(us_add_confirmed_grouped_x.apply(lambda x: x.date()))
    us_add_confirmed_grouped_dict = {date: case_num for date, case_num in
                                     zip(us_add_confirmed_grouped_x, list(us_add_confirmed_grouped['Cases']))}
    us_add_confirmed_grouped_x = sorted(us_add_confirmed_grouped_x)
    us_add_confirmed_grouped_y = [us_add_confirmed_grouped_dict[date] for date in us_add_confirmed_grouped_x]
    # 绘制折线图
    line = Line(init_opts=opts.InitOpts())

    # 添加X,Y数据
    line.add_xaxis(xaxis_data=us_add_confirmed_grouped_x)
    line.add_yaxis(series_name='美国累计确诊病例趋势', y_axis=us_add_confirmed_grouped_y)

    # 添加折线图配置
    line.set_global_opts(title_opts=opts.TitleOpts(title='美国累计确诊病例趋势'))
    pages.add(line)
    
    """

    # 输出pages
    pages.render('全球新冠疫情情况.html')
Exemplo n.º 18
0
def draw_multiple_map(month, day):
    page = Page(layout=Page.SimplePageLayout)
    city_map = {
        "西双版纳": "西双版纳傣族自治州",
        "大理": "大理白族自治州",
        "红河": "红河哈尼族自治州",
        "德宏": "德宏傣族景颇族自治州",
        "甘孜州": "甘孜藏族自治州",
        "凉山": "凉山彝族自治州",
        "阿坝州": "阿坝藏族羌族自治州",
        "黔东南州": "黔东南苗族侗族自治州",
        "黔西南州": "黔西南依族苗族自治州",
        "黔南州": "黔南布依族苗族自治州",
        "湘西自治州": "湘西土家族苗族自治州",
        "恩施": "恩施土家族苗族自治州"
    }
    for p in get_province_data(month, day):
        title = '%s-%d例' % (p['provinceShortName'], p['confirmedCount'])

        # 城市
        labels = []
        for city in p['cities']:
            city_name = city['cityName']
            if p['provinceShortName'] in ['重庆', '上海', '北京', '天津']:
                labels.append(city_name)
            elif city_name in city_map:
                labels.append(city_map[city_name])
            else:
                labels.append(city_name + "市")

        # 数量
        counts = [city['confirmedCount'] for city in p['cities']]
        if len(labels) == 0:
            continue
        province_map = Map(
            init_opts=opts.InitOpts(width='350px', height='380px'))
        province_map.add("", [list(z) for z in zip(labels, counts)],
                         p['provinceShortName'])
        province_map.set_series_opts(label_opts=opts.LabelOpts(font_size=8))
        province_map.set_global_opts(
            title_opts=opts.TitleOpts(title=title),
            legend_opts=opts.LegendOpts(is_show=False),
            visualmap_opts=opts.VisualMapOpts(pieces=[
                {
                    'min': 1000,
                    'color': '#450704'
                },
                {
                    'max': 999,
                    'min': 500,
                    'color': '#75140B'
                },
                {
                    'max': 499,
                    'min': 200,
                    'color': '#AD2217'
                },
                {
                    'max': 199,
                    'min': 10,
                    'color': '#DE605B'
                },
                {
                    'max': 9,
                    'color': '#FFFEE7'
                },
            ],
                                              is_piecewise=True,
                                              is_show=False),
        )
        page.add(province_map)

    root = 'html-charts/%d%d' % (month, day)
    create_dir(root)
    page.render('%s/省份地图.html' % root)
Exemplo n.º 19
0
site_counts_211 = df_211['site'].value_counts()
dict_site_211 = {'name': site_counts_211.index, 'counts': site_counts_211.values}
data_211 = pd.DataFrame(dict_site_211)
sum_211_counts = data_211['counts'].sum()
data_211['rate'] = data_211['counts'].apply(lambda x: x / sum_211_counts)

df_985_211 = pd.concat([df_211, df_985], ignore_index=True)
site_counts_985_211 = df_985_211['site'].value_counts()
dict_site_985_211 = {'name': site_counts_985_211.index, 'counts': site_counts_985_211.values}
data_985_211 = pd.DataFrame(dict_site_985_211)
sum_985_211_counts = data_985_211['counts'].sum()
data_985_211['rate'] = data_985_211['counts'].apply(lambda x: x / sum_985_211_counts)


# 柱状图页面
page = Page()
# 各地区高校数量柱状图
bar = Bar()
bar.add_xaxis(data['name'].values.tolist())
bar.add_yaxis("", data['counts'].values.tolist())
bar.set_global_opts(
    xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=45)),
    title_opts=opts.TitleOpts(title="各地区高校数量"),
    datazoom_opts=opts.DataZoomOpts()
)
bar.set_series_opts(itemstyle_opts={
    "normal": {
        "color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(0, 244, 255, 1)'
                }, {
Exemplo n.º 20
0
                    min_=0,
                    max_=2000,
                    pos_top='center',
                ),  #调整图例参数
                title_opts=opts.TitleOpts(title="全国Java招聘数量分布图",
                                          pos_left='center')))

    return c


def geo_heatmap() -> Geo:
    c = (Geo().add_schema(maptype="china").add(
        "",
        [list(z) for z in zip(citys[:120], City_Avg_Salary[:120])],
        type_=ChartType.HEATMAP,
    ).set_series_opts(label_opts=opts.LabelOpts(
        is_show=False)).set_global_opts(
            visualmap_opts=opts.VisualMapOpts(
                pos_top='center',
                min_=0,
                max_=15000,
            ),
            title_opts=opts.TitleOpts(title="全国Java薪资分布图", pos_left='center'),
        ))
    return c


page = Page()
page.add(geo_base(), geo_heatmap())
page.render('全国岗位薪资分布图.html')
Exemplo n.º 21
0
def pyecharts(request):
    """dashboard view"""
    # 工单数量统计
    chart_dao = ChartDao()
    data = chart_dao.workflow_by_date(30)
    today = date.today()
    one_month_before = today - relativedelta(days=+30)
    attr = chart_dao.get_date_list(one_month_before, today)
    _dict = {}
    for row in data['rows']:
        _dict[row[0]] = row[1]
    value = [_dict.get(day) if _dict.get(day) else 0 for day in attr]
    bar1 = Bar()
    bar1.add_xaxis(attr)
    bar1.add_yaxis("月统计", value)
    bar1.set_global_opts(title_opts=opts.TitleOpts(title='SQL上线工单统计(数量)'),
                         datazoom_opts=opts.DataZoomOpts(is_show=True),
                         toolbox_opts=opts.ToolboxOpts(is_show=True))

    # 工单按组统计
    data = chart_dao.workflow_by_group(30)
    attr = [row[0] for row in data['rows']]
    value = [row[1] for row in data['rows']]
    pie1 = Pie()
    pie1.set_global_opts(title_opts=opts.TitleOpts(title='SQL上线工单统计(组)'),
                         legend_opts=opts.LegendOpts(orient="vertical",
                                                     pos_top="15%",
                                                     pos_left="2%"))
    pie1.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    pie1.add("", [list(z) for z in zip(attr, value)])

    # 工单按人统计
    data = chart_dao.workflow_by_user(30)
    attr = [row[0] for row in data['rows']]
    value = [row[1] for row in data['rows']]
    bar2 = Bar()
    bar2.add_xaxis(attr)
    bar2.add_yaxis("月统计", value)
    bar2.set_global_opts(title_opts=opts.TitleOpts(title='SQL上线工单统计(用户)'))

    # SQL语句类型统计
    data = chart_dao.syntax_type()
    attr = [row[0] for row in data['rows']]
    value = [row[1] for row in data['rows']]
    pie2 = Pie()
    pie2.set_global_opts(title_opts=opts.TitleOpts(title='SQL上线工单统计(类型)'),
                         legend_opts=opts.LegendOpts(orient="vertical",
                                                     pos_top="15%",
                                                     pos_left="2%"))
    pie2.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    pie2.add("", [list(z) for z in zip(attr, value)])

    # SQL查询统计(每日检索行数)
    attr = chart_dao.get_date_list(one_month_before, today)
    effect_data = chart_dao.querylog_effect_row_by_date(30)
    effect_dict = {}
    for row in effect_data['rows']:
        effect_dict[row[0]] = int(row[1])
    effect_value = [
        effect_dict.get(day) if effect_dict.get(day) else 0 for day in attr
    ]
    count_data = chart_dao.querylog_count_by_date(30)
    count_dict = {}
    for row in count_data['rows']:
        count_dict[row[0]] = int(row[1])
    count_value = [
        count_dict.get(day) if count_dict.get(day) else 0 for day in attr
    ]
    line1 = Line()
    line1.set_global_opts(title_opts=opts.TitleOpts(title='SQL查询统计'),
                          legend_opts=opts.LegendOpts(selected_mode='single'))
    line1.add_xaxis(attr)
    line1.add_yaxis("检索行数",
                    effect_value,
                    markpoint_opts=opts.MarkPointOpts(
                        data=[opts.MarkPointItem(type_="average")]))
    line1.add_yaxis("检索次数",
                    count_value,
                    is_smooth=True,
                    markline_opts=opts.MarkLineOpts(data=[
                        opts.MarkLineItem(type_="max"),
                        opts.MarkLineItem(type_="average")
                    ]))

    # SQL查询统计(用户检索行数)
    data = chart_dao.querylog_effect_row_by_user(30)
    attr = [row[0] for row in data['rows']]
    value = [int(row[1]) for row in data['rows']]
    pie4 = Pie()
    pie4.set_global_opts(title_opts=opts.TitleOpts(title='SQL查询统计(用户检索行数)'),
                         legend_opts=opts.LegendOpts(orient="vertical",
                                                     pos_top="15%",
                                                     pos_left="2%"))
    pie4.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    pie4.add("", [list(z) for z in zip(attr, value)])

    # SQL查询统计(DB检索行数)
    data = chart_dao.querylog_effect_row_by_db(30)
    attr = [row[0] for row in data['rows']]
    value = [int(row[1]) for row in data['rows']]
    pie5 = Pie()
    pie5.set_global_opts(title_opts=opts.TitleOpts(title='SQL查询统计(DB检索行数)'),
                         legend_opts=opts.LegendOpts(orient="vertical",
                                                     pos_top="15%",
                                                     pos_left="2%"))
    pie5.set_series_opts(
        label_opts=opts.LabelOpts(formatter="{b}: {c}", position="left"))

    pie5.add("", [list(z) for z in zip(attr, value)])

    # 可视化展示页面
    page = Page(layout=Page.SimplePageLayout)
    page.add(bar1, pie1, bar2, pie2, line1, pie4, pie5)
    return render(request, "dashboard.html", {"chart": page.render_embed()})
Exemplo n.º 22
0
def theme_walden() -> Bar:
    c = (Bar(init_opts=opts.InitOpts(theme=ThemeType.WALDEN)).add_xaxis(
        Faker.choose()).add_yaxis("商家A", Faker.values()).add_yaxis(
            "商家B", Faker.values()).add_yaxis("商家C", Faker.values()).add_yaxis(
                "商家D", Faker.values()).set_global_opts(
                    title_opts=opts.TitleOpts("Theme-walden")))
    return c


@C.funcs
def theme_westeros() -> Bar:
    c = (Bar(init_opts=opts.InitOpts(theme=ThemeType.WESTEROS)).add_xaxis(
        Faker.choose()).add_yaxis("商家A", Faker.values()).add_yaxis(
            "商家B", Faker.values()).add_yaxis("商家C", Faker.values()).add_yaxis(
                "商家D", Faker.values()).set_global_opts(
                    title_opts=opts.TitleOpts("Theme-westeros")))
    return c


@C.funcs
def theme_wonderland() -> Bar:
    c = (Bar(init_opts=opts.InitOpts(theme=ThemeType.WONDERLAND)).add_xaxis(
        Faker.choose()).add_yaxis("商家A", Faker.values()).add_yaxis(
            "商家B", Faker.values()).add_yaxis("商家C", Faker.values()).add_yaxis(
                "商家D", Faker.values()).set_global_opts(
                    title_opts=opts.TitleOpts("Theme-wonderland")))
    return c


put_html(Page().add(*[fn() for fn, _ in C.charts]).render_notebook())
Exemplo n.º 23
0
data = [('广东', 54558), ('台湾', 49564), ('上海', 37677), ('北京', 14690),
        ('浙江', 9062), ('江苏', 4226), ('河北', 4216), ('天津', 4017), ('福建', 2358),
        ('香港', 1667), ('山东', 1427), ('江西', 1119), ('湖南', 863), ('河南', 847),
        ('湖北', 377), ('黑龙江', 341), ('海南', 226), ('四川', 101), ('山西', 38),
        ('安徽', 36), ('辽宁', 34), ('陕西', 32), ('贵州', 28), ('吉林', 27), ('重庆', 1)]


class Collector:
    charts = []

    @staticmethod
    def funcs(fn):
        Collector.charts.append((fn, fn.__name__))


C = Collector()


@C.funcs
def map_world() -> Map:
    c = (Map().add("中国省份分布", data, "china").set_global_opts(
        title_opts=opts.TitleOpts(title="Map-VisualMap(连续型)"),
        visualmap_opts=opts.VisualMapOpts(max_=54558),
    ))
    return c


Page().add(*[fn()
             for fn, _ in C.charts]).render('./output/map_china_province.html')
Exemplo n.º 24
0
                            "%s_vehicles" % site_list[i]))
        y_data_duration.append(
            generate_y_axis(x_data, res_duration_list[i],
                            "%s_duration" % site_list[i]))
        y_data_distance.append(
            generate_y_axis(x_data, res_distance_list[i],
                            "%s_distance" % site_list[i]))

    # sys.stdout.write("Type of the whole result is: ")
    # 使用stdout可以不换行输出
    # print(type(res_vehicle_disney))
    # sys.stdout.write("Type of the a single result is: ")
    # print(type(res_vehicle_disney[0]))
    # sys.stdout.write("The result is: \n")
    # print(res_vehicle_disney)
    # print(type(res_vehicle_disney[0]['yearweek(begin_timestamp,1)']))

    # print(x_data)
    # print(x_data_temp)

    page = Page()
    line1 = draw_test(x_data_temp, y_data_vehicle, "每周投入车辆(单位:辆)", "投入车辆数")
    page.add(line1)

    line2 = draw_test(x_data_temp, y_data_duration, "每周总测试时间(单位:小时)", "测试小时数")
    page.add(line2)

    line3 = draw_test(x_data_temp, y_data_distance, "每周总测试里程(单位:公里)", "公里")
    page.add(line3)
    page.render("111.html")
Exemplo n.º 25
0
def page_layout1() -> Page:
    page = Page(layout=Page.SimplePageLayout)
    page.add(sex_distribution_bar(), sex_distribution_pie())
    return page
Exemplo n.º 26
0
                     datazoom_opts=opts.DataZoomOpts(range_start= start,range_end= 100))
    #.set_global_opts()


    #.render("China_1_Daily_C_vs_P.html")
)

e= (
    Line()
    .add_xaxis(mydate)
    .add_yaxis("Positive", pos,is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=False),)
    .add_yaxis("Negative", neg,is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=False),)


    .set_global_opts(title_opts=opts.TitleOpts(title="Weekly Media Effect In HongKong"),
                     #tooltip_opts=opts.TooltipOpts(is_show=False),

                     #legend_opts=opts.LegendOpts(textstyle_opts={"fontSize": 20}),
                     #graphic_textstyle_opts = opts.GraphicTextStyleOpts(font='2em "STHeiti", sans-serif'),
                     datazoom_opts=opts.DataZoomOpts(range_start= start,range_end= 100))
    #.set_global_opts()


    #.render("China_1_Daily_C_vs_P.html")
)
page = Page(layout=Page.SimplePageLayout)
page.add(c,d,e)
page.render('./res/'+str(time.time())+'WeeklySuicide.html')
Exemplo n.º 27
0
from example.commons import Collector, Faker
from pyecharts import options as opts
from pyecharts.charts import Bar, Page
"""
Created on 19-5-09
@title: ''
@author: XuChao
"""

# 直方图
if __name__ == "__main__":

    C = Collector()

    @C.funcs
    def bar_base() -> Bar:
        num_people_py = [37, 240, 1, 22]
        # java
        num_people_java = [44, 239, 2, 15]
        degree = ['大专', '本科', '硕士', '不限']

        c = (Bar().add_xaxis(degree).add_yaxis(
            "java", num_people_java).add_yaxis(
                "python",
                num_people_py).set_global_opts(title_opts=opts.TitleOpts(
                    title="对学历要求", subtitle="数据由拉勾网提供")))
        return c

    Page().add(*[fn() for fn, _ in C.charts]).render("d1.html")
Exemplo n.º 28
0
    },
    brush_opts=opts.BrushOpts(),
    toolbox_opts=opts.ToolboxOpts(),
    datazoom_opts=[opts.DataZoomOpts(),
                   opts.DataZoomOpts(type_="inside")],
    tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
    visualmap_opts=opts.VisualMapOpts(max_=120))

data_pair = [list(z) for z in zip(x, y)]
data_pair.sort(key=lambda x: x[1])

pie = Pie()
pie.add(
    series_name="电影国家分布",
    data_pair=data_pair[:],
    radius="70%",
)
pie.set_global_opts(
    title_opts=opts.TitleOpts(title="电影国家分布饼状图"),
    legend_opts=opts.LegendOpts(orient="vertical",
                                pos_left="5%",
                                pos_top="20%"),
    #        visualmap_opts=opts.VisualMapOpts(max_=120)
)
pie.set_series_opts(tooltip_opts=opts.TooltipOpts(
    trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"))

page = Page(layout=Page.SimplePageLayout)
page.add(pie)
page.add(bar)
page.render('templates/test.html')
Exemplo n.º 29
0
    data = []
    for i in range(101):
        theta = i / 100 * 360
        r = 5 * (1 + math.sin(theta / 180 * math.pi))
        data.append([r, theta])
    hour = [i for i in range(1, 25)]
    c = (Polar().add_schema(angleaxis_opts=opts.AngleAxisOpts(
        data=hour, type_="value", boundary_gap=False, start_angle=0)).add(
            "love", data,
            label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                title_opts=opts.TitleOpts(title="Polar-Love")))
    return c


@C.funcs
def polar_flower() -> Polar:
    data = []
    for i in range(361):
        t = i / 180 * math.pi
        r = math.sin(2 * t) * math.cos(2 * t)
        data.append([r, i])
    c = (Polar().add_schema(
        angleaxis_opts=opts.AngleAxisOpts(start_angle=0, min_=0)).add(
            "flower", data,
            label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                title_opts=opts.TitleOpts(title="Polar-Flower")))
    return c


Page().add(*[fn() for fn, _ in C.charts]).render()
Exemplo n.º 30
0
def test_page_jshost_default():
    bar = _create_bar()
    line = _create_line()
    page = Page().add(bar, line)
    assert_equal(page.js_host, "https://assets.pyecharts.org/assets/")