Exemplo n.º 1
0
def multi_follower_counts(c1, c2, c3, c4, c5):
    # 不同赞数区间内的粉丝数分布统计
    _, y1 = data_sort(list(c1.index), list(c1))
    _, y2 = data_sort(list(c2.index), list(c2))
    _, y3 = data_sort(list(c3.index), list(c3))
    _, y4 = data_sort(list(c4.index), list(c4))
    _, y5 = data_sort(list(c5.index), list(c5))
    x = [
        '<50', '50-100', '100-500', '0.5k-1k', '1k-5k', '5k-10k', '1w-5w',
        '5w-10w', '10w-50w', '50w-100w', '>100w'
    ]

    line = (Line().add_xaxis(x).add_yaxis('赞同数为1k-4k', y1).add_yaxis(
        '赞同数为4k-10k', y2).add_yaxis('赞同数为10k-20k', y3).add_yaxis(
            '赞同数为20k-40k',
            y4).add_yaxis('赞同数为40k以上', y5).extend_axis(yaxis=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts())).set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                    linestyle_opts=opts.LineStyleOpts(
                        width=2)).set_global_opts(
                            title_opts=opts.TitleOpts(title='赞数-粉丝数统计'),
                            xaxis_opts=opts.AxisOpts(
                                axislabel_opts=opts.LabelOpts(rotate=30),
                                name='粉丝数'),
                            yaxis_opts=opts.AxisOpts(
                                axislabel_opts=opts.LabelOpts()),
                            tooltip_opts=opts.TooltipOpts(
                                trigger="axis", axis_pointer_type="cross"),
                            legend_opts=opts.LegendOpts(pos_left="right")))

    filename = '赞数-粉丝数统计-line.html'
    line.render(filename)
    print('图表创建成功')

    bar = (Bar().add_xaxis(x).add_yaxis('赞同数为1k-4k', y1).add_yaxis(
        '赞同数为4k-10k', y2).add_yaxis('赞同数为10k-20k', y3).add_yaxis(
            '赞同数为20k-40k',
            y4).add_yaxis('赞同数为40k以上', y5).extend_axis(yaxis=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts())).set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                    linestyle_opts=opts.LineStyleOpts(
                        width=2)).set_global_opts(
                            title_opts=opts.TitleOpts(title='赞数-粉丝数统计'),
                            xaxis_opts=opts.AxisOpts(
                                axislabel_opts=opts.LabelOpts(rotate=30),
                                name='粉丝数'),
                            yaxis_opts=opts.AxisOpts(
                                axislabel_opts=opts.LabelOpts()),
                            tooltip_opts=opts.TooltipOpts(
                                trigger="axis", axis_pointer_type="cross"),
                            legend_opts=opts.LegendOpts(pos_left="right")))

    filename = '赞数-粉丝数统计-bar.html'
    bar.render(filename)
    print('图表创建成功')

    page = Page(layout=Page.SimplePageLayout)
    page.add(line, bar)
    page.render("赞数-粉丝数统计.html")
    print('图表创建成功')
Exemplo n.º 2
0
def hu_run_select() -> 'html':
    the_region = request.form["the_region_selected"]
    print(the_region)  # 检查用户输入
    dfs = df1.query("CountryName=='{}'".format(the_region))

    gdp_df = getCsvData('GDP.csv')  # 读取GDP.csv 数据内容
    select_df = getCsvData('select_nation.csv')  # 读取select_nation.csv 数据内容
    fig1 = map_world_gdp(gdp_df)
    fig2 = pie_base(select_df)
    fig3 = bar_datazoom_select(select_df)
    fig4 = line_markpoint(select_df)

    page = Page(layout=Page.SimplePageLayout)
    page.add(fig1, fig2, fig3, fig4)
    page.render("child2.html")

    with open("templates/child2.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    data_str = dfs.to_html()
    return render_template('results2.html',
                           the_plot_all=plot_all,
                           the_res=data_str,
                           the_select_region=regions_available,
                           )
Exemplo n.º 3
0
def seller_chart():
    follower_num = []
    order_num = []
    for s in Seller.objects.order_by('-order_num')[:30]:
        order_num.append([s.name, s.order_num])

    for s in Seller.objects.filter().order_by('-followers_num')[:30]:
        follower_num.append([s.name, s.followers_num])

    follower_num_pie = Pie(init_opts=opts.InitOpts(js_host='../static/js/', width='1100px')
                           ).add('', follower_num, radius=["10%", "75%"],
                                 # center=["25%", "50%"],
                                 rosetype="radius", ).set_global_opts(
        title_opts=opts.TitleOpts(title="订阅数"),
        legend_opts=opts.LegendOpts(
            orient="vertical", pos_top="15%", pos_left="100px", type_='scroll'
        ),
    )
    order_num_pie = Pie(init_opts=opts.InitOpts(js_host='../static/js/', width='1100px')
                        ).add('', order_num, radius=["10%", "75%"],
                              # center=["25%", "50%"],
                              rosetype="radius", ).set_global_opts(
        title_opts=opts.TitleOpts(title="订单数"),
        legend_opts=opts.LegendOpts(
            orient="vertical", pos_top="15%", pos_left="100px", type_='scroll'
        ),
    )

    page = Page(layout=Page.SimplePageLayout, js_host='../static/js/')
    page.add(order_num_pie, follower_num_pie)
    return page.render_embed()
Exemplo n.º 4
0
def page(data, name):

    # 页面所有图表
    page = Page(layout=Page.DraggablePageLayout)
    page.page_title = name
    page.add(kline(data=data), line_shouyi(data=data))
    return page
Exemplo n.º 5
0
def report_factor_performance(factors: pd.DataFrame, name: str):
    """评估单个因子的表现

    :param factors:
    :param name: 因子名称
    :return:
    """
    nb_cols = [x for x in factors.columns if x.startswith("n")]
    page = Page(layout=Page.DraggablePageLayout, page_title=f"{name} - 性能分析")
    box_data = {
        col: [factors[col].quantile(v) for v in [0, 0.25, 0.5, 0.75, 1]]
        for col in nb_cols
    }
    chart = box_plot(data=box_data,
                     title=f"BASE",
                     width=f'{40*len(nb_cols)}px',
                     height='300px')
    page.add(chart)
    for k, df in factors.groupby(name):
        box_data = {
            col: [df[col].quantile(v) for v in [0, 0.25, 0.5, 0.75, 1]]
            for col in nb_cols
        }
        chart = box_plot(data=box_data,
                         title=f"{name}@{k}",
                         width=f'{40*len(nb_cols)}px',
                         height='300px')
        page.add(chart)
    return page
Exemplo n.º 6
0
def draw_multiple_pie_02(month, day):
    max_width, max_height = 1400, 3000

    page = Page(layout=Page.SimplePageLayout)
    h_center, v_center = 10, 40
    horizontal_step, vertical_step = 350, 320
    pies = []
    for p in get_province_data(month, day):
        title = '%s-%d例' % (p['provinceShortName'], p['confirmedCount'])
        labels = [city['cityName'] for city in p['cities']]
        counts = [city['confirmedCount'] for city in p['cities']]
        if len(labels) == 0:
            continue
        pie = Pie(init_opts=opts.InitOpts(width='{}px'.format(horizontal_step),
                                          height='{}px'.format(vertical_step)))
        pie.set_global_opts(legend_opts=opts.LegendOpts(is_show=False),
                            title_opts=opts.TitleOpts(title))
        pie.add(
            title,
            [list(z) for z in zip(labels, counts)],
            radius=[5, 80],
            # center=[h_center + 150, v_center + 110]
        ).set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"),
                          tooltip_opts=opts.TooltipOpts())

        h_center += horizontal_step
        if h_center + 200 > max_width:
            h_center = 10
            v_center += vertical_step
        page.add(pie)

    root = 'html-charts/%d%d' % (month, day)
    create_dir(root)
    page.render('%s/省份信息2.html' % root)
    page.render('provinces.html')
Exemplo n.º 7
0
    def draw(self,
             data_list: typing.List[ClassifierResult],
             report_path: str = None):
        # draw
        line = self._draw_line(data_list)
        bar = self._draw_bar(data_list)

        # merge charts
        page = Page()
        page.add(line)
        page.add(bar)

        # insert extras
        template = Template(TEMPLATE)
        template_content = template.render(
            chart=Markup(page.render_embed()),
            dir_link_list=self.dir_link_list,
            thumbnail_list=self.thumbnail_list,
        )

        # save to file
        if not report_path:
            report_path = f'{toolbox.get_timestamp_str()}.html'
        with open(report_path, "w") as fh:
            fh.write(template_content)
        logger.info(f'save report to {report_path}')
    def show_dlt(self):
        red_balls = []
        blue_balls = []
        with open(self.input_file, 'r') as f:
            for i in range(Config.PAGES * Config.ITEMS_PER_PAGE):
                one_line_data = f.readline().strip()
                # print(one_line_data)
                red_balls.extend([
                    int(one_line_data[15 + (2 * i):15 + (2 * (i + 1))])
                    for i in range(5)
                ])
                blue_balls.append(int(one_line_data[-4:-2]))
                blue_balls.append(int(one_line_data[-2:]))

        red_counter = Counter(red_balls)
        blue_counter = Counter(blue_balls)
        # print(red_balls)
        # print(blue_balls)
        # print(red_counter)
        # print(blue_counter)
        # print(red_counter.most_common())
        # print(blue_counter.most_common())
        red_dict = {}
        blue_dict = {}
        for i in red_counter.most_common():
            red_dict['{}'.format(i[0])] = i[1]

        for j in blue_counter.most_common():
            blue_dict['{}'.format(j[0])] = j[1]

        print(red_dict)
        print(blue_dict)

        red_list = sorted(red_counter.most_common(),
                          key=lambda number: number[0])
        blue_list = sorted(blue_counter.most_common(),
                           key=lambda number: number[0])
        print(blue_list)
        print(red_list)

        # 红球图表添加
        red_bar = Bar()
        red_x = ['{}'.format(str(x[0])) for x in red_list]
        red_y = ['{}'.format(str(x[1])) for x in red_list]
        red_bar.add_xaxis(red_x)
        red_bar.add_yaxis('红色球出现的次数', red_y)
        # 篮球图表添加
        blue_bar = Bar()
        blue_x = ['{}'.format(str(x[0])) for x in blue_list]
        blue_y = ['{}'.format(str(x[1])) for x in blue_list]
        blue_bar.add_xaxis(blue_x)
        blue_bar.add_yaxis('蓝色球出现的次数',
                           blue_y,
                           itemstyle_opts=opts.ItemStyleOpts(color='blue'))

        page = Page(page_title='大乐透数据分析', interval=3)
        page.add(red_bar)
        page.add(blue_bar)

        page.render(self.output_file)
Exemplo n.º 9
0
def page(filename="info"):
    '''
    页面
    '''
    # test data

    y_data = [{
        'name': '安卓',
        'values': [0.34, 0.76, 0.88, 0.99, 0.242, 0.42, 0.22]
    }, {
        'name': 'ios',
        'values': [0.50, 0.90, 0.72, 0.34, 0.76, 0.88, 0.99]
    }]
    x_data = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

    page = Page()
    page.add(
        # timeline_bar_reversal(title='渠道留存'),
        liquid_data_precision("111"),
        bar_datazoom_slider("222",
                            y_data=y_data,
                            x_data=x_data,
                            datazoom_opts=None,
                            toolbox_opts=None),
        table_base("333"),
        line_markpoint("555"),
        pie_rosetype("444"),
        grid_mutil_yaxis("777"),
    )
    page.render('{}.html'.format(filename))
def DrawIng():
    page = Page(
        page_title = "coding4.county"
    )
    page.add(timeline_map())
    page.add(timeline_bar())
    page.render("4.county.html")
Exemplo n.º 11
0
def draw_order_signals(trader_name, render='html'):
    df_account = get_account(trader_name=trader_name)
    start_timestamp = df_account['timestamp'][0]
    end_timestamp = df_account['timestamp'][-1]

    df_orders = get_orders(trader_name=trader_name)
    grouped = df_orders.groupby('security_id')

    page = Page()

    for security_id, order_df in grouped:
        kdata = get_kdata(security_id=security_id,
                          provider='netease',
                          start_timestamp=start_timestamp,
                          end_timestamp=end_timestamp)
        mark_points = order_df
        kline = draw_kline(df_list=[kdata],
                           markpoints_list=[mark_points],
                           render=None)

        page.add(kline)

    if render == 'html':
        file_name = '{}_signals'.format(trader_name)
        page.render(get_ui_path(file_name))
    elif render == 'notebook':
        page.render_notebook()

    return page
Exemplo n.º 12
0
def create_teach_bar(*dfs) -> Bar:
    def create_one_bar(df, day=None):
        df = df.sort_values(['rank', 'teach'])
        am_values = df.query('apm=="上午"')
        pm_values = df.query('apm=="下午"')
        names = am_values['teach'].values.tolist()

        title = f'({day})教师课时数' if day else '教师课时数'

        b = (
            Bar().add_xaxis(names).add_yaxis(
                '上午', am_values['value'].values.tolist(),
                stack="stack1").add_yaxis('下午',
                                          pm_values['value'].values.tolist(),
                                          stack="stack1")
            # .reversal_axis()
            .set_series_opts(label_opts=opts.LabelOpts(
                is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title=title),
                    datazoom_opts=opts.DataZoomOpts(type_='slider',
                                                    range_start=0,
                                                    range_end=10),
                ))
        return b

    if len(dfs) == 1:
        return create_one_bar(dfs[0])

    page = Page()

    for df in dfs:
        day = df['day'].iloc[0]
        b = create_one_bar(df, day)
        page.add(b)
    return page
Exemplo n.º 13
0
def page_simple_layout(redmineObj, project_name, query_id, tracker_name):
    myIssue = MyIssue(redmine)
    myTracker = MyTracker(redmine)
    # 数据获取
    if query_id is not None:
        issues = myIssue.get_issues_by_query_id(project_name, query_id)
        all_issues = issues
    else:
        all_issues = myIssue.get_issues(project_name, None,
                                        None)  # 根据项目获取所有issue
        tracker_id = myTracker.get_trackerId_by_name(
            tracker_name)  # 跟踪标签需要手动填,不同项目跟踪标签不同
        issues = myIssue.get_issues(project_name, tracker_id,
                                    None)  # 根据tacker_id获取项目内或者自定义查询内的issue
    issues_time = myIssue.stat_issue_by_createOrClose_time(
        issues)  # 获取issues中的创建时间和关闭时间
    priority_data = myIssue.get_issues_by_priority(issues)
    assign_to_data = myIssue.stat_issue_by_assignTo(issues)
    tracker_bug_data = myIssue.get_issues_by_tracker(all_issues)

    # 制作统计图
    priority_pie = draw_pie_bug_priority(priority_data)  # 按优先级统计BUG
    assign_to_pie = draw_pie_bug_agent(assign_to_data)  # 按指派人统计BUG
    time_line = draw_line_bug_time(issues_time)  # 按创建时间/关闭时间统计BUG
    tracker_pie = draw_pie_bug_tracker(tracker_bug_data)  # 按跟踪标签统计Issue
    page = Page(layout=Page.SimplePageLayout)
    page.add(tracker_pie, priority_pie, assign_to_pie, time_line)
    page.render("./reports/redmine.html")
Exemplo n.º 14
0
def draw_account(trader_name):
    df_account = get_account(trader_name=trader_name)
    df_position = get_position(trader_name=trader_name)

    xdata = [to_time_str(timestamp) for timestamp in df_account.index]
    ydata = df_account.loc[:, 'all_value'].values.tolist()

    line = (Line().add_xaxis(xdata).add_yaxis("市值曲线", ydata).set_global_opts(
        title_opts=opts.TitleOpts(title="Grid-Line", pos_top="48%"),
        legend_opts=opts.LegendOpts(pos_top="48%"),
    ))

    time_line = Timeline()
    for timestamp in df_position.index:
        positions = zip(
            df_position.loc[timestamp, ['security_id']].values.tolist(),
            df_position.loc[timestamp, ['value']].values.tolist())
        security_positions = [(x[0], y[0]) for x, y in positions]
        print(security_positions)
        pie = Pie().add("持仓", security_positions)
        time_line.add(pie, to_time_str(timestamp))

    page = Page()
    page.add(line, time_line)

    return page
Exemplo n.º 15
0
def hu_run_select() -> 'html':
    try:
        df = pd.read_csv("GDP per person.csv")
        the_region = request.form["the_region_selected"]  # 年份勾选
        log.info("勾选年份为{0}".format(the_region))
        fig5 = bar_gdp([country_ls, data3[the_region]])
        fig6 = grid_mutil_yaxis(
            [country_ls, data3[the_region], data4[the_region]],
            ["GDP增长率(%)", "生育率(%)"])
        fig7 = map_data([countries, data2[the_region]], "识字率",
                        "1990-2017女性识字率世界地图")
        fig8 = map_data([countries, data1[the_region]], "生育率",
                        "1990-2017青春期女性生育率世界地图")

        page = Page(layout=Page.SimplePageLayout)
        page.add(fig5, fig6, fig7, fig8)
        page.render("task2.html")
        with open("task2.html", encoding="utf8", mode="r") as f:
            plot_all = "".join(f.readlines())

        data_str = df.to_html()
        return render_template(
            'results2.html',
            the_plot_all=plot_all,
            the_res=data_str,
            the_select_region=regions_available,
        )
    except Exception as ex:
        log.error("页面数据请求失败: {0}".format(str(ex)))
        return None
Exemplo n.º 16
0
def page_draggable_layout():
    page = Page(layout=Page.DraggablePageLayout)
    page.add(
        chinamap(),
        bar_sale(),
    )
    page.render("面板图.html")
Exemplo n.º 17
0
def page_simple_layout():
    page = Page()
    page.add(
        line2(),
        bar1(),
        gauge1(),
    )
    page.render("C:/Users/suqi/Desktop/allcode/page_simple_layoutnew.html")
Exemplo n.º 18
0
 def combine_charts(self):
     # 若有大于一个以上的图表,将它们合为一个图表(Page类型)
     # 不直接画到一个图表上,是因为在web app中无法直接嵌入Page类型,而其他模式均可以
     if len(self._charts) > 1:
         page = Page()
         page.add(*self._charts)
         self._charts.clear()
         self.save_chart(page)
Exemplo n.º 19
0
def paint_together(country='China'):
    page = Page(layout=Page.SimplePageLayout)
    page.add(
        paint_country_summary_chart(country),
        paint_confirmed_distributed_chart(country),
        paint_treemap(),
    )
    return page.dump_options_with_quotes()
Exemplo n.º 20
0
def Gather_in_Page():
    Data_List = [['项目2',25.02]]
    bg= BG()
    page = Page(layout=Page.DraggablePageLayout)
    page.add(bg)
    for NPS_List in Data_List:
        gauge = NPS(NPS_List)
        page.add(gauge)
    page.render('NPS.html')
Exemplo n.º 21
0
def page_layout():
    page = Page(layout=Page.DraggablePageLayout)
    page.add(
        map_world(),
        timeline_suicides(),
        bar_suicides_no(),
        bar_suicides_100k(),
    )
    page.render("page.html")
Exemplo n.º 22
0
def page_plays(data1,data2,user_id):
    bar = draw_bar_plays(data1, user_id)
    line = draw_line_clip(data2, user_id)
    page = Page(layout=Page.SimplePageLayout)
    page.add(
        bar,
        line,
    )
    #page.render("page_simple_layout.html")
    return page
Exemplo n.º 23
0
def Page_Layout(request):
    page = Page(layout=Page.DraggablePageLayout)
    page.add(Rating_Pie(), Rating_line_bar(), Score_by_time_douban(),
             Score_by_time_maoyan(), Map_amount(), scatter_rating_likes(),
             grid_liquid_favorate_rate(), WordCloud_douban_high(),
             WordCloud_douban_low(), WordCloud_maoyan_high(),
             WordCloud_maoyan_low(), sex_distribution_bar(),
             sex_distribution_pie(), level_distribution_bar(),
             level_distribution_pie(), Evaluate_bar())
    return HttpResponse(page.render_embed())
Exemplo n.º 24
0
def page_simple_layout():
    page = Page(layout=Page.SimplePageLayout)
    page.add(
        course_selection_ranking(),
        class_sum_by_subject(),
        subject_pie(),
        word_cloud(),
    )
    page.page_title = "MOOC当前开放课程可视化"
    page.render("当前全部开放课程可视化.html")
Exemplo n.º 25
0
def page_layout(list, title, name):
    page = Page(layout=Page.SimplePageLayout)
    page.add(
        death_histogram(list, title, name),
        CumulativeDeaths_histogram(list, title, name),
        Confirmed_histogram(list, title, name),
        CumulativeConfirmed_histogram(list, title, name),
        timeline(list, title, name),
    )
    page.render("templates/COVID/" + name + '.html')
Exemplo n.º 26
0
def page_draggable_layout():
    page = Page(layout=Page.DraggablePageLayout)
    page.add(
        bar_datazoom_slider(),
        line_markpoint(),
        pie_rosetype(),
        grid_mutil_yaxis(),
        liquid_data_precision(),
        table_base(),
    )
    page.render()
def page_default_layout():
    page = Page()
    page.add(
        bar_datazoom_slider(),
        line_markpoint(),
        pie_rosetype(),
        grid_mutil_yaxis(),
        liquid_data_precision(),
        table_base(),
    )
    put_html(page.render_notebook())
Exemplo n.º 28
0
def draw_multiple_map(month, day):
    page = Page(layout=Page.SimplePageLayout)
    size = ('1000px', '1000px')

    # 全国疫情地图
    labels, counts = get_province_status(month, day)
    country_map = get_map(labels=labels, counts=counts,
                          title='全国-%s例' % get_total_statistic(month, day)['confirmedCount'], size=size, where='china',
                          pieces=get_default_pieces())
    page.add(country_map)
    page.render('全国新冠数据地理分布展示.html')
Exemplo n.º 29
0
def plot_all():
    chart1 = valuation_report()
    chart2 = tail_northup()
    chart3 = tail_zxqh()


    page = Page()
    page.add(chart1, chart2, chart3)
    output_path = os.path.join(PROJECT_DIR, "utils/output/统计指标.html")
    page.render(output_path)
    return "utils/output/统计指标.html"
Exemplo n.º 30
0
def _get_new_page(unique: bool = True) -> Page:
    bar = _create_bar()
    line = _create_line()

    if not unique:
        bar.chart_id = "chenjiandongx_is_an_awesome_boy"
        line.chart_id = "chenjiandongx_is_an_amazing_boy"

    p = Page(layout=Page.DraggablePageLayout)
    p.add(bar, line)
    return p