예제 #1
0
def show_bar(id):
    fix_data()
    bar = Bar(init_opts=opts.InitOpts(
        width='1200px', height='800px', page_title='page'))
    bar.add_xaxis(fix_id)
    bar.add_yaxis('线程', fix_time, stack="stack1", color=Faker.rand_color())
    bar.reversal_axis()
    bar.set_global_opts(title_opts=opts.TitleOpts(title="压测时间图"),
                        datazoom_opts=opts.DataZoomOpts(orient="vertical"))
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                        markpoint_opts=opts.MarkPointOpts(data=[
                            opts.MarkPointItem(type_="max", name="最大值"),
                            opts.MarkPointItem(type_="min", name="最小值"),
                            opts.MarkPointItem(type_="average", name="平均值"),
                        ]))
    bar.render('压力测试{}.html'.format(id + 1))
예제 #2
0
def bar(keywords):
    xaxis = []
    yaxis = []
    for i in keywords:
        xaxis.append(i[0])
        yaxis.append(i[1])

    bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.WALDEN))
    bar.add_xaxis(xaxis[:25])
    bar.add_yaxis("重要性", yaxis[:25])

    bar.set_global_opts(title_opts=opts.TitleOpts(title='TF-IDF Ranking'))
    bar.set_global_opts(toolbox_opts=opts.ToolboxOpts(is_show=True))
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    bar.reversal_axis()
    return bar
예제 #3
0
def analyze_country():
    #lambda表达式进行以空格分开,并返回列表
    countryList = reduce(lambda x, y: x + y, list(df['Country'].apply(lambda x: x.split(' '))))
    #进行分类统计
    countryDic = Counter(countryList)
    #将字典转为DataFrame
    country_dataframe = pd.DataFrame.from_dict(countryDic, orient='index')
    print(country_dataframe)
    country = list(country_dataframe.index)
    num = list(country_dataframe.iloc[:, 0])

    bar = Bar()
    bar.add_xaxis(country[:10])
    bar.add_yaxis("各国家电影数量Top10", num[:10])
    bar.set_global_opts(title_opts=opts.TitleOpts(title="各国家电影数量Top10"))
    bar.render("./html_files/country.html")
예제 #4
0
def create_percent_stack_bar(title, x_list, data_list, data_unit):
    """
        :param title: 图表名称
        :param x_list: 横坐标内容为时间序列,纵坐标高度为多个(同级)指标的总和,具体各个指标的数值、比例以不同颜色标出
        :param data_list: 字典{key1:value1,key2:value2...},构成柱状图的多个不同类型的bar
        :param data_unit: y轴的数值单位
        :return:
        """
    # 数据格式重构:
    count = len(x_list)   # 数据期数
    sumList = []            # 汇总
    for i in range(count):
        sumList.append(0)
    for key in data_list.keys():
        for i in range(count):
            if data_list[key][i] is not None:           #   空数据处理
                sumList[i] = sumList[i] + data_list[key][i]
    for key in data_list.keys():
        value_list = []
        for i in range(count):
            new_dic = {}
            new_dic["value"] = data_list[key][i]
            if data_list[key][i] is not None:           #   空数据处理,sumList[i]不会为None或为0,指标选择时已经做了规避
                new_dic["percent"] = data_list[key][i]/sumList[i]
            else:
                new_dic["percent"] = None
            value_list.append(new_dic)
        data_list[key] = value_list

    c = Bar(init_opts=opts.InitOpts(theme=THEME_TYPE))
    c.add_xaxis(x_list)
    for key in data_list.keys():
        c.add_yaxis(key, data_list[key],stack="stack1")         # stack参数设置层叠样式

    c.set_series_opts(label_opts=opts.LabelOpts(position="right",
                      formatter=JsCode(
                        "function(x){console.log(x);return Number(x.data.percent * 100).toFixed() + '%';}"
                      )))
    c.set_global_opts(title_opts=opts.TitleOpts(title=title),
                      legend_opts=opts.LegendOpts(pos_left="right"),
                      yaxis_opts=opts.AxisOpts(name="单位:" + data_unit))

    src_path = "./指标-年度-图片生成/"
    html_file_name = src_path + title + ".html"
    img_file_name = src_path + title + ".png"
    make_snapshot(snapshot, c.render(html_file_name), img_file_name)
    print(img_file_name+":生成完毕...")
예제 #5
0
def dsp_gcc():  # 显示遗传相关

    import xlrd
    # file = "breeding.xlsx"
    f1 = xlrd.open_workbook(file)
    sheet1 = f1.sheet_by_name('Sheet1')
    lst = gcc(file)[0]  # 接收计算的早选指数
    y = []
    colorArr = [
        '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
        'F'
    ]
    for i in range(len(lst)):
        color = "#"
        for j in range(6):
            color += colorArr[random.randint(0, 14)]

        y.append(
            opts.BarItem(
                value=lst[i],
                itemstyle_opts=opts.ItemStyleOpts(color=str(color)),
                # itemstyle_opts=opts.ItemStyleOpts(color=color[i])
            ))
    x_ax = gcc(file)[1]
    y_ax = []

    bar = Bar(init_opts=opts.InitOpts(  #bg_color='rgba(255,250,205,0.2)',
        width="1800px", height="800px"))
    bar.set_colors(["#FF6347", "black"])
    bar.add_xaxis(x_ax)
    bar.add_yaxis("遗传相关", y, category_gap="60%")
    bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max", name="最大值")]))
    # bar.add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])
    bar.set_global_opts(title_opts=opts.TitleOpts(title="显示已有数据遗传相关"))
    for i in range(sheet1.nrows - 1):
        y_ax.append(i)
    line = Line(init_opts=opts.InitOpts(width="1800px", height="800px"))
    line.add_xaxis(y_ax)
    line.add_yaxis(series_name="",
                   y_axis=lst,
                   label_opts=opts.LabelOpts(is_show=True))
    picture = bar.overlap(line)
    return render_template("display.html",
                           picture_options=picture.dump_options())
예제 #6
0
def bar_chart():
    # 柱状图

    bar = Bar()
    x_y_axis = get_chart_data()
    bar.add_xaxis(x_y_axis[0])
    for j in x_y_axis[1]:
        for key, value in j.items():
            bar.add_yaxis(key, value, label_opts=opts.LabelOpts(is_show=False))
    bar.set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[
        opts.MarkPointItem(type_="max", name="最大值"),
        opts.MarkPointItem(type_="min", name="最小值"),
    ]), )
    bar.set_global_opts(
        title_opts=opts.TitleOpts(
            title="API耗时统计",
            subtitle="生产环境",
            pos_left="30%",
            title_textstyle_opts=opts.TextStyleOpts(color='red'),
            subtitle_textstyle_opts=opts.TextStyleOpts(color='blue')),
        xaxis_opts=opts.AxisOpts(
            name="运行时间",
            type_="category",
            boundary_gap=True,
            # axislabel_opts=opts.LabelOpts(rotate=15)
        ),
        yaxis_opts=opts.AxisOpts(name="实际的响应时间(单位:秒)",
                                 # min_=0,
                                 # max_=20
                                 ),
        legend_opts=opts.LegendOpts(type_='scroll',
                                    selected_mode='multiple',
                                    pos_left='right',
                                    pos_top='10%',
                                    orient='vertical'),
        tooltip_opts=opts.TooltipOpts(trigger="axis",
                                      axis_pointer_type="line"),
        toolbox_opts=opts.ToolboxOpts(is_show=True, pos_left='right'),
        visualmap_opts=opts.VisualMapOpts(is_show=True,
                                          type_="size",
                                          min_=0,
                                          max_=20,
                                          range_text=["最大值", "最小值"]),
        datazoom_opts=[opts.DataZoomOpts(range_start=50, range_end=100)],
    )
    bar = bar.dump_options_with_quotes()
    return bar
예제 #7
0
파일: views.py 프로젝트: joestarhu/jhutool
def workhour_get():
    p = WorkhourInfo()
    # 获取最近的12月
    df = p.df.dropna()[-12:]

    xdata = df['月份'].tolist()
    # fig = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
    fig = Bar()

    fig.add_xaxis(xdata)
    fig.add_yaxis('总投入',
                  df['实际投入工时'].tolist(),
                  label_opts=opts.LabelOpts(position='inside'))
    for v in df.columns[6:]:
        fig.add_yaxis(v,
                      df[v].tolist(),
                      stack='detail',
                      is_selected=False,
                      label_opts=opts.LabelOpts(is_show=False))

    fig.set_global_opts(
        title_opts=opts.TitleOpts(title="最近12月工时投入"),
        tooltip_opts=opts.TooltipOpts(is_show=True,
                                      trigger="axis",
                                      axis_pointer_type="shadow"),
        yaxis_opts=opts.AxisOpts(name='工时'),
    )

    #"""
    df['投入总工时比率'] = (df['投入总工时比率'] * 100).round(0)
    maxratio = df['投入总工时比率'].max()
    maxratio = 100 if maxratio <= 100 else maxratio
    ratio = df['投入总工时比率'].tolist()

    line = Line()
    line.add_xaxis(xdata)
    line.add_yaxis('投入工时率', ratio, yaxis_index=1)

    fig.extend_axis(yaxis=opts.AxisOpts(name="投入工时率",
                                        type_="value",
                                        min_=0,
                                        max_=maxratio,
                                        axislabel_opts=opts.LabelOpts(
                                            formatter="{value} %")))
    fig.overlap(line)
    #"""
    return fig.dump_options_with_quotes()
예제 #8
0
def process_statistics():
    para = {'size': 80}
    data_source = requests.post("http://localhost:7000/es_virus_data",
                                data=json.dumps(para)).json()
    # 得出地理信息/感染数量/
    confirmedCount_province_list = {}
    suspectedCount_province_list = {}
    curedCount_province_list = {}
    deadCount_province_list = {}
    for source in province_souce['hits']['hits']:
        base = source['_source']
        provinceShortName = base['provinceShortName']
        confirmedCount = base['confirmedCount']
        suspectedCount = base['suspectedCount']
        curedCount = base['curedCount']
        deadCount = base['deadCount']
        # print('{}-{}-{}-{}-{}'.format(provinceShortName,confirmedCount,suspectedCount,curedCount,deadCount))
        if provinceShortName not in confirmedCount_province_list.keys():
            confirmedCount_province_list[provinceShortName] = int(
                confirmedCount)
        if provinceShortName not in suspectedCount_province_list.keys():
            suspectedCount_province_list[provinceShortName] = int(
                suspectedCount)
        if provinceShortName not in curedCount_province_list.keys():
            curedCount_province_list[provinceShortName] = int(curedCount)
        if provinceShortName not in deadCount_province_list.keys():
            deadCount_province_list[provinceShortName] = int(deadCount)
    provinces = list(confirmedCount_province_list.keys())
    confirm_list = list(confirmedCount_province_list.values())
    suspect_list = list(suspectedCount_province_list.values())
    cure_list = list(curedCount_province_list.values())
    dead_list = list(deadCount_province_list.values())
    # bar = Line()
    bar = Bar()
    bar.add_xaxis(provinces)
    bar.add_yaxis("确诊", confirm_list, stack="stack1")
    bar.add_yaxis("疑似", suspect_list, stack="stack1")
    bar.add_yaxis("治愈", cure_list, stack="stack1")
    bar.add_yaxis("死亡", dead_list, stack="stack1")
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True))
    bar.set_global_opts(title_opts=opts.TitleOpts(title="省份疫情统计"))
    return bar


# if __name__ == '__main__':
#     process_statistics()
예제 #9
0
파일: views.py 프로젝트: joestarhu/jhutool
def member_month_workhour():
    p = PJinfo()
    m = p.member_workhour_get()
    tl = Timeline()

    li_month = sorted(m.keys(), reverse=True)
    for i in li_month:
        month = m[i].sort_values(0, axis=1, ascending=False)
        fig = Bar()
        fig.add_xaxis(month.columns.tolist())
        fig.add_yaxis('投入工时', month.values.flatten().tolist())
        fig.set_global_opts(
            title_opts=opts.TitleOpts(title=f"2020年{i}月人员工时投入"),
            yaxis_opts=opts.AxisOpts(name='工时'),
        )
        tl.add(fig, time_point=f'{i}月')
    return tl.dump_options_with_quotes()
예제 #10
0
def do_baidu_charts():
    nvshen = pd.read_csv('nvshen_new.csv')
    nvshen.sort_values('aip_score', ascending=False, inplace=True)
    bar = Bar()
    name_top = nvshen['name'][0:10]
    name_bottom = nvshen['name'][-10:-1]
    name = name_top.values.tolist() + name_bottom.values.tolist()
    score_top = nvshen["aip_score"][0:10]
    score_bottom = nvshen["aip_score"][-10:-1]
    score = score_top.values.tolist() + score_bottom.values.tolist()
    bar.add_xaxis(name)
    bar.add_yaxis("女神新得分/百分制", score)
    bar.set_global_opts(
        datazoom_opts=opts.DataZoomOpts(is_show=True, orient="vertical"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-45)),
        toolbox_opts=opts.ToolboxOpts())
    bar.render('女神新排名.html')
예제 #11
0
def draw_balance_bar(xaxis,
                     yaxis,
                     difference=None,
                     title="消费统计",
                     markline=None,
                     width=2000) -> Bar:
    """
    x = [月_日, 月_日, 月_日, ....]
    y = [(title1, [num1, num2, num3, num4, ...]), (title2, [num1, num2, num3, num4, ...])]
    :param difference: 差值 (比如:收入100,消费80,差值就是20) : ['title', [1,2,3,4]]
    :param xaxis: x轴
    :param yaxis: y轴
    :param title: 标题
    :param markline: 标记辅助线
    :param width: 宽
    :return: Bar
    """
    bar = Bar()
    bar.add_xaxis(xaxis)
    for name, axis in yaxis:
        bar.add_yaxis(name, axis, category_gap="20%", gap="0%")
    bar.set_global_opts(title_opts=opts.TitleOpts(title=title, ),
                        datazoom_opts=[
                            opts.DataZoomOpts(range_start=0, range_end=100),
                            opts.DataZoomOpts(type_="inside")
                        ],
                        tooltip_opts=opts.TooltipOpts(
                            trigger='axis', axis_pointer_type='shadow'))
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

    if difference:
        name, diff_yaxis = difference
        line = Line().add_xaxis(xaxis).add_yaxis(
            name,
            diff_yaxis,
            symbol_size=15,
            z_level=1,
            is_symbol_show=False,
        )
        bar.overlap(line)

    if markline is not None:
        bar.set_series_opts(markline_opts=opts.MarkLineOpts(
            data=[opts.MarkLineItem(y=markline, name='预算')]))

    return bar
예제 #12
0
def bar_markline_type():
    obj_bar = Bar()
    obj_bar.add_xaxis(Faker.choose())
    obj_bar.add_yaxis("商家A",Faker.values())
    obj_bar.add_yaxis("商家B",Faker.values())
    obj_bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show = False),
        markline_opts=opts.MarkPointOpts(
            data = [
                opts.MarkLineItem(type_="min", name="最小值"),
                opts.MarkLineItem(type_="max", name="最大值"),
                opts.MarkLineItem(type_="average", name="平均值"),
            ]
        )
    )
    obj_bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-MarkLine(指定类型)", subtitle="平均值的线"))
    return obj_bar
예제 #13
0
def bar_datazoom_slider(xaxis,yaxis_name,yaxis,title_name) -> Bar:
   
    if isinstance(yaxis_name,str):
            c=(
        Bar()
        .add_xaxis(xaxis)
        .add_yaxis(yaxis_name,yaxis)
        .set_global_opts(
            title_opts=opts.TitleOpts(title=title_name),
            datazoom_opts=[opts.DataZoomOpts()],
            brush_opts=opts.BrushOpts(),
            toolbox_opts=opts.ToolboxOpts(),
            legend_opts=opts.LegendOpts(is_show=False),
            yaxis_opts=opts.AxisOpts(name="我是 Y 轴"),
            xaxis_opts=opts.AxisOpts(name="我是 X 轴"),
        )
    )
    elif isinstance(yaxis,list):
        c=Bar()
        c.add_xaxis(xaxis)
        for i in range(len(yaxis_name)):
            c.add_yaxis(yaxis_name[i],yaxis[i], gap="0%",category_gap="10%",is_selected=True)
        c.set_global_opts(
            title_opts=opts.TitleOpts(title=title_name),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
            #datazoom_opts=opts.DataZoomOpts(orient="vertical"),
            brush_opts=opts.BrushOpts(),
            toolbox_opts=opts.ToolboxOpts(),
            legend_opts=opts.LegendOpts(is_show=False),
            yaxis_opts=opts.AxisOpts(name="我是 Y 轴"),
            xaxis_opts=opts.AxisOpts(name="我是 X 轴"),
        )
        c.set_series_opts(
        label_opts=opts.LabelOpts(is_show=True),
        markpoint_opts=opts.MarkPointOpts(
            data=[
                opts.MarkPointItem(type_="max", name="最大值"),
                opts.MarkPointItem(type_="min", name="最小值"),
                opts.MarkPointItem(type_="average", name="平均值"),
            ]
        )
        )              
  
    
    return c
예제 #14
0
파일: test.py 프로젝트: QMXDD/Crawler
    def table(self):
        file = open(self.name + "_title.txt", "r", encoding="utf-8")
        title = []
        read = []
        list = file.readlines()
        for i in list:

            pos = None
            end = i.__len__() - 1
            while end >= 0:
                if (i[end] == " "):
                    pos = end
                    break
                end -= 1
            pos2 = None
            while end >= 0:
                if (i[end] != " "):
                    pos2 = end + 1
                    break
                end -= 1

            title_str = i[:pos2]
            j = title_str.__len__()
            j = int(j / 2)
            title_str = title_str[:j] + "\n" + title_str[j:]
            title.append(title_str)

            read_str = i[pos:]
            read_str = read_str.strip()
            read.append(int(read_str))

        read_data = []
        title_data = []
        j = 0
        for i in read:
            if i > self.num:
                read_data.append(i)
                title_data.append(title[j])
            j += 1

        bar = Bar()
        bar.add_xaxis(title_data)
        bar.add_yaxis("访问量大于" + str(self.num) + "的博客", read_data)
        bar.reversal_axis()
        bar.render(self.name + ".html")
예제 #15
0
def bar_markpoint_custom():
    x, y = Faker.choose(), Faker.values()
    obj_bar = Bar()
    obj_bar.add_xaxis(x)
    obj_bar.add_yaxis("A",
                      y,
                      # 自定义标注点,设置在这里obj_bar.add_yaxis,只有一个系列图标注,
                      # 如果该参数设置到obj_bar.set_series_opts,所有系列柱的指定柱就会标注该点,但值是一样的是第一个系列柱的值
                      markpoint_opts=opts.MarkPointOpts(
                          data=[opts.MarkPointItem(name="自定义标记点", coord=[x[2], y[2]], value=y[2])]
                      ))
    obj_bar.add_yaxis("B", Faker.values())
    # 设置标签不显示
    obj_bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),
    )
    obj_bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-MarkPoint(自定义)", subtitle="副标题"))
    return obj_bar
예제 #16
0
파일: echart.py 프로젝트: a1192138141/boss
def get_education_background():
    bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
    bar.set_global_opts(title_opts=opts.TitleOpts(title="学历占比", ),
                        legend_opts=opts.LegendOpts(pos_left="20%"))
    bar.add_xaxis(education)
    value = []
    for i in education:
        where = {
            'experience': {
                '$regex': ".*" + i + ".*"
            },
        }
        count = mongodb.get_count_by_where(where)
        value.append(count)

    bar.add_yaxis("要求学历招聘", value, bar_width=20)
    bar.set_colors("blue")
    return (bar)
예제 #17
0
def bar_base():
    # 今天日期
    todaydate = datetime.date.today()

    # 时间周期-横坐标
    date_periods = []
    for i in range(6, 0, -1):
        date_i = todaydate - datetime.timedelta(days=i)
        date_periods.append(date_i)
    date_periods_day = [str(date.day) + '日' for date in date_periods]

    bar = Bar()
    bar.add_xaxis(date_periods_day)
    bar.add_yaxis("商家A", [randrange(0, 100) for _ in range(6)])
    bar.add_yaxis("商家B", [randrange(0, 100) for _ in range(6)])
    title_options = opts.TitleOpts(title="群发数据统计", subtitle="最近7日数据")
    bar.set_global_opts(title_opts=title_options)
    return bar
예제 #18
0
def vw_pyecharts():
    data = xlrd.open_workbook('./data/xlrd-data.xlsx')
    sheet_table = data.sheets()[0]
    xdata = []
    ydata = []
    for i in range(1, sheet_table.nrows):
        print(sheet_table.row_values(i))
        xdata.append(sheet_table.row_values(i)[0])
        ydata.append(sheet_table.row_values(i)[1])

    print(xdata)
    print(ydata)

    # 数据可视化,柱状图
    bar = Bar()
    bar.add_xaxis(xdata)
    bar.add_yaxis("名称1", ydata)
    bar.render("show.html")
예제 #19
0
def bar_graphic_component():
    obj_bar = Bar()
    obj_bar.add_xaxis(Faker.choose())
    obj_bar.add_yaxis("商家A", Faker.values())
    obj_bar.add_yaxis("商家B", Faker.values())
    obj_bar.set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-Graphic 组件示例", subtitle="副标题"),
        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"
                            ),
                        ),
                    )
                ]
            )

    )
    return obj_bar
예제 #20
0
def most_appear_per_chapter():
    """
    每一回出场次数最多的角色
    用柱状图进行可视化
    :return:
    """
    jieba.load_userdict("character.txt")  # 加载人物 nr
    character_list = []
    with open('character.txt', encoding='utf-8') as r:
        lines = r.readlines()
    for line in lines:
        name = line.split(',')[0]
        character_list.append(name)

    counts_per_chapter = []
    char_per_chapter = []

    for i in range(120):
        with open('chapters/' + str(i + 1) + '.txt', encoding='utf-8') as r:
            text = r.read()
        p = pseg.cut(text)  # return: generator

        fre_char_dist = OrderedDict()
        for word, tag in p:
            if tag == 'nr' and word in character_list:
                if word in fre_char_dist.keys():
                    fre_char_dist[word] += 1
                else:
                    fre_char_dist[word] = 1

        key = list(fre_char_dist.keys())[0]
        counts_per_chapter.append(fre_char_dist[key])
        char_per_chapter.append(key + '-第' + str(i + 1) + '回')
        fre_char_dist.clear()
    # print(len(counts_per_chapter))
    # print(len(char_per_chapter))
    bar = Bar()
    bar.add_xaxis(char_per_chapter)
    bar.add_yaxis('频次', counts_per_chapter)
    bar.set_global_opts(title_opts=opts.TitleOpts(title="红楼梦每一回出场次数最多的人物"),
                        toolbox_opts=opts.ToolboxOpts(),
                        datazoom_opts=[opts.DataZoomOpts()])
    bar.render('most_appear_per_chapter.html')
예제 #21
0
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
예제 #22
0
    def _draw_bar(data_list: typing.List[ClassifierResult]) -> Bar:
        # draw bar chart
        bar = Bar()
        x_axis = sorted(list(set([i.stage for i in data_list])))
        y_axis = list()
        offset = data_list[1].timestamp - data_list[0].timestamp
        for each_stage_name in x_axis:
            each_stage = sorted([i for i in data_list if i.stage == each_stage_name], key=lambda x: x.frame_id)
            time_cost = each_stage[-1].timestamp - each_stage[0].timestamp + offset
            y_axis.append(time_cost)

        bar.add_xaxis(x_axis)
        bar.add_yaxis('time cost', y_axis)
        bar.set_global_opts(
            title_opts=opts.TitleOpts(title="Time Cost"),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
        )
        logger.debug(f'time cost: {dict(zip(x_axis, y_axis))}')
        return bar
예제 #23
0
파일: ChartModel.py 프로젝트: Sijiu/Xbill
def draw_balance_bar(balance_axis: BalanceAxis, title="收支统计", markline=None, width=2000) -> Bar:
    bar = Bar()
    bar.add_xaxis(balance_axis.x_axis)

    for name, axis in balance_axis.y_axis.items():
        bar.add_yaxis(name, axis, category_gap="20%", gap="0%")

    bar.set_global_opts(title_opts=opts.TitleOpts(title=title, ),
                        datazoom_opts=[opts.DataZoomOpts(range_start=0, range_end=100),
                                       opts.DataZoomOpts(type_="inside")],
                        tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='shadow'))

    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

    if markline is not None:
        bar.set_series_opts(markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(y=markline, name='预算')]),
                            )

    return bar
예제 #24
0
    def average_salary_bar(self):
        option_list = []
        option_dict = {}
        for i in self.data.col_values(8, 1):
            if i not in option_list:
                option_list.append(i)
            if not option_dict.get(i):
                option_dict[i] = int(0)

        for i in self.data.col_values(8, 1):
            option_dict[i] = option_dict[i] + 1

        option_value_list = list(option_dict.values())
        bar = Bar()
        bar.add_xaxis(option_list)
        print(type(option_value_list))
        bar.add_yaxis("平均薪资", option_value_list)
        bar.set_global_opts(title_opts=opts.TitleOpts(title="平均薪资"))
        bar.render("average_salary.html")
예제 #25
0
def draw_bar(x, mid, legends, name):
    bar = Bar(init_opts={"width": "3000px", "height": "600px"})
    # bar.add_xaxis(x)

    assert len(mid) == len(legends)

    bar.add_xaxis(x)

    for j in range(len(mid)):
        bar.add_yaxis(mid[j], legends[j], stack="stack")

    bar.set_global_opts(xaxis_opts=opts.AxisOpts(
        axislabel_opts=opts.LabelOpts(rotate=18, font_size=10)),
                        title_opts=opts.TitleOpts(title=f"X={name}"))
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

    SAVE_PATH = ".." + os.sep + "img" + os.sep + f"{name}.html"
    bar.render(SAVE_PATH)
    a = 1
def main():
    refresh_cookie()
    provices = {}
    for date in DATE:
        result = query(date)
        for item in result:
            name = item['name']
            provices.setdefault(name, [])
            provices[name].append(item['total'])
    if len(provices.keys()) == 0:
        return

    bar = Bar()
    bar.add_xaxis(DATE)

    for p in provices.keys():
        bar.add_yaxis(p, provices[p])

    bar.render('housing_sales_area.html')
예제 #27
0
def bar_markpoint_type():
    obj_bar = Bar()
    obj_bar.add_xaxis(Faker.choose())
    obj_bar.add_yaxis("A", Faker.values())
    obj_bar.add_yaxis("B", Faker.values())
    # 设置标签不显示
    obj_bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),
        # 标注指定类型的点
        markpoint_opts=opts.MarkPointOpts(
            data =[
                opts.MarkPointItem(type_="max",name="最大值"),
                opts.MarkPointItem(type_="min", name="最小值"),
                opts.MarkPointItem(type_="average", name="平均值")
            ]
        )
    )
    obj_bar.set_global_opts(title_opts=opts.TitleOpts(title="Bar-MarkPoint(指定类型)", subtitle="副标题"))
    return obj_bar
예제 #28
0
def bar_base(ts_codes) -> Bar:
    assert ts_codes is not None, '股票代码为空'
    # if ts_codes is None:
    #     ts_codes = ['000001.SZ']
    df = readProfits(ts_codes)
    print(df)
    c = Bar()
    stocks = []
    for key, data in df.iteritems():
        if key == 'end_date':
            c.add_xaxis(data.to_list())
        else:
            name = readStockName(key)
            title = f'{key} {name}'
            stocks.append(title)
            c.add_yaxis(title, data.to_list())
    c.set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例",
                                                subtitle=', '.join(stocks)))
    return c
예제 #29
0
def paintGraph(contestInfo, starttime='2017-09', endtime='2020-07'):
    # 先根据指定的起始日期和截止日期构造需要的数据
    x, cf, ac, nc, jsk, total = [], [], [], [], [], []
    for key, value in sorted(contestInfo.items()):
        if key >= starttime and key <= endtime:
            x.append(key)
            cf.append({'value': value.get('cf', 0)})
            ac.append({'value': value.get('ac', 0)})
            nc.append({'value': value.get('nc', 0)})
            jsk.append({'value': value.get('jsk', 0)})
            total.append(value.get('total', 0))

    # print(total)

    # 绘制图表
    bar = Bar(
        init_opts=opts.InitOpts(theme=ThemeType.LIGHT, page_title='各年月比赛数量统计'))
    bar.set_global_opts(title_opts=opts.TitleOpts(title='各年月比赛数量统计'),
                        xaxis_opts=opts.AxisOpts(name='比赛年月'),
                        yaxis_opts=opts.AxisOpts(name='比赛数量统计'))
    bar.add_xaxis(x)
    bar.add_yaxis("CodeForces", cf, stack="stack1", category_gap="50%")
    bar.add_yaxis("NowCoder", nc, stack="stack1", category_gap="50%")
    bar.add_yaxis("AtCoder", ac, stack="stack1", category_gap="50%")
    bar.add_yaxis("计蒜客", jsk, stack="stack1", category_gap="50%")
    bar.set_series_opts(label_opts=opts.LabelOpts(
        position="inside",
        formatter=JsCode(
            "function(x){return x.data.value ? Number(x.data.value) : '';}"),
    ))

    line = Line()
    line.set_global_opts(
        tooltip_opts=opts.TooltipOpts(is_show=False),
        xaxis_opts=opts.AxisOpts(type_="category"),
        yaxis_opts=opts.AxisOpts(
            type_="value",
            axistick_opts=opts.AxisTickOpts(is_show=True),
            splitline_opts=opts.SplitLineOpts(is_show=True),
        ),
    )
    line.add_xaxis(xaxis_data=x)
    line.add_yaxis(
        series_name="total",
        y_axis=total,
        symbol="Circle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=True),
    )

    # 将柱状图与折线图一起输出到html文件中
    bar.overlap(line).render('acmersite02.html')
예제 #30
0
파일: views.py 프로젝트: gqxie/kangni
def timeline_bar():
    cursor = connection.cursor()
    cursor.execute("""SELECT
                DATE_FORMAT( rev.create_time, '%Y-%m-%d' ) create_time,
                revt.`name`,
                count( * )
            FROM
                resource_event rev
                LEFT JOIN resource_eventtype revt ON rev.event_type_id = revt.id
            GROUP BY
                create_time,
                event_type_id""")
    rows = cursor.fetchall()
    name_list = []
    event_type_list = []
    for row in rows:
        name = row[0]
        if name not in name_list:
            name_list.append(name)
        event_type = row[1]
        if event_type not in event_type_list:
            event_type_list.append(event_type)

    tl = Timeline(init_opts=opts.InitOpts(height="350px"))

    for day in name_list:
        bar = Bar()
        bar.add_xaxis(['违章记录'])

        for i in range(len(event_type_list)):
            event_type_name = event_type_list[i]
            num = 0
            for row in rows:
                if day == row[0] and event_type_name == row[1]:
                    num = row[2]
                    break

            bar.add_yaxis(event_type_name, [num])

        bar.set_global_opts(title_opts=opts.TitleOpts("{}".format(day)))
        tl.add(bar, "{}".format(day))
    return tl.render_embed()