Example #1
0
def test_bar_stack():
    bar = Bar("柱状图数据堆叠示例")
    bar.add("商家A", CLOTHES, clothes_v1, is_stack=True)
    bar.add("商家B", CLOTHES, clothes_v2, is_stack=True)
    html_content = bar._repr_html_()
    assert "dataZoom" not in html_content
    assert "stack_" in html_content
Example #2
0
def create_three():
    page = Page(page_title=TEST_PAGE_TITLE)

    # bar
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图数据堆叠示例")
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True)
    page.add(bar)

    # scatter3D
    import random
    data = [
        [random.randint(0, 100),
         random.randint(0, 100),
         random.randint(0, 100)] for _ in range(80)
        ]
    scatter3d = Scatter3D("3D 散点图示例", width=1200, height=600)
    scatter3d.add("", data, is_visualmap=True, visual_range_color=RANGE_COLOR)
    page.add(scatter3d)

    # guangdong
    value = [20, 190, 253, 77, 65]
    attr = ['汕头市', '汕尾市', '揭阳市', '阳江市', '肇庆市']
    map = Map("广东地图示例", width=1200, height=600)
    map.add("", attr, value, maptype='广东', is_visualmap=True,
            visual_text_color='#000')
    page.add(map)

    return page
Example #3
0
def test_grid_top_bottom():
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=720)
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True)
    line = Line("折线图示例", title_top="50%")
    line.add(
        "最高气温",
        WEEK,
        [11, 11, 15, 13, 12, 13, 10],
        mark_point=["max", "min"],
        mark_line=["average"],
    )
    line.add(
        "最低气温",
        WEEK,
        [1, -2, 2, 5, 3, 2, 0],
        mark_point=["max", "min"],
        mark_line=["average"],
        legend_top="50%",
    )

    grid = Grid()
    grid.add(bar, grid_bottom="60%")
    grid.add(line, grid_top="60%")
    grid.render()
Example #4
0
def create_a_bar(title):
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar(title)
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True)
    return bar
Example #5
0
def test_numpy_array():
    v1 = np.array([5, 20, 36, 10, 75, 90])
    bar = Bar(TITLE)
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    html = bar.render_embed()
    json_encoded_title = json.dumps(TITLE)
    assert json_encoded_title in html
Example #6
0
def test_grid_add_overlap():
    from pyecharts import Overlap

    grid = Grid()

    attr = ["{}月".format(i) for i in range(1, 13)]
    v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
    v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
    v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]

    bar = Bar("Overlap+Grid 示例", width=1200, height=600, title_pos="40%")
    bar.add("蒸发量", attr, v1)
    bar.add(
        "降水量",
        attr,
        v2,
        yaxis_formatter=" ml",
        yaxis_max=250,
        legend_pos="85%",
        legend_orient="vertical",
        legend_top="45%",
    )

    line = Line()
    line.add("平均温度", attr, v3, yaxis_formatter=" °C")

    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line, is_add_yaxis=True, yaxis_index=1)

    grid.add(overlap, grid_right="20%")
    grid.render()
Example #7
0
def ax_draw_macd(axes, kdata, n1=12, n2=26, n3=9):
    """绘制MACD
    
    :param axes: 指定的坐标轴
    :param KData kdata: KData
    :param int n1: 指标 MACD 的参数1
    :param int n2: 指标 MACD 的参数2
    :param int n3: 指标 MACD 的参数3
    """
    macd = MACD(CLOSE(kdata), n1, n2, n3)
    bmacd, fmacd, smacd = macd.getResult(0), macd.getResult(1), macd.getResult(2)
    
    text = 'MACD(%s,%s,%s) DIF:%.2f, DEA:%.2f, BAR:%.2f'%(n1,n2,n3,fmacd[-1],smacd[-1],bmacd[-1])
    #axes.text(0.01,0.97, text, horizontalalignment='left', verticalalignment='top', transform=axes.transAxes)
    total = len(kdata)
    x_list = [i for i in range(total)]
    y1_list = [round(x) if x > 0 else '-' for x in bmacd]
    y2_list = [round(x) if x <= 0 else '-' for x in bmacd]
    
    style = gcf().get_style(axes)
    bar = Bar(subtitle=text, title_pos='10%', title_top='8%')
    bar.add('1', x_list, y1_list, is_stack=True, is_legend_show=False, **style)
    bar.add('2', x_list, y2_list, is_stack=True, is_legend_show=False, **style)
    
    axes.add(bar)
    fmacd.plot(axes=axes, line_type='dotted')
    smacd.plot(axes=axes)

    gcf().add_axis(axes)
    return gcf()
def test_grid_properties():
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=720)
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True)
    line = Line("折线图示例", title_top="50%")
    line.add(
        "最高气温",
        WEEK,
        [11, 11, 15, 13, 12, 13, 10],
        mark_point=["max", "min"],
        mark_line=["average"],
    )
    line.add(
        "最低气温",
        WEEK,
        [1, -2, 2, 5, 3, 2, 0],
        mark_point=["max", "min"],
        mark_line=["average"],
        legend_top="50%",
    )

    grid = Grid(width=1024, height=768)
    grid.add(bar, grid_bottom="60%")
    grid.add(line, grid_top="60%")
    eq_(grid.width, 1024)
    eq_(grid.height, 768)
    assert (
        ("echarts" in bar.js_dependencies)
        or ("echarts.min" in bar.js_dependencies)
    )
Example #9
0
def test_grid_four_direction():
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=720, width=1200, title_pos="65%")
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True, legend_pos="80%")
    line = Line("折线图示例")
    line.add("最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"], mark_line=["average"])
    line.add("最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"], mark_line=["average"],
             legend_pos="20%")
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    scatter = Scatter("散点图示例", title_top="50%", title_pos="65%")
    scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%")
    es = EffectScatter("动态散点图示例", title_top="50%")
    es.add("es", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0],
           effect_scale=6, legend_top="50%", legend_pos="20%")

    grid = Grid()
    grid.add(bar, grid_bottom="60%", grid_left="60%")
    grid.add(line, grid_bottom="60%", grid_right="60%")
    grid.add(scatter, grid_top="60%", grid_left="60%")
    grid.add(es, grid_top="60%", grid_right="60%")
    grid.render()
Example #10
0
def test_bar_rotate_label():
    days = ["{}天".format(i) for i in range(20)]
    days_v1 = [random.randint(1, 20) for _ in range(20)]
    bar = Bar("坐标轴标签旋转示例")
    bar.add("", days, days_v1, xaxis_interval=0, xaxis_rotate=30,
            yaxis_rotate=30)
    assert "stack_" not in bar._repr_html_()
Example #11
0
def test_bar_datazoom_undefined():
    days = ["{}天".format(i) for i in range(30)]
    days_v1 = [random.randint(1, 30) for _ in range(30)]
    bar = Bar("Bar - datazoom 默认 示例")
    bar.add("", days, days_v1, is_label_show=True, is_datazoom_show=True)
    html_content = bar._repr_html_()
    assert "dataZoom" in html_content
    assert ': "slider"' in html_content
    assert ': "inside"' not in html_content
Example #12
0
def test_bar_datazoom_inside():
    days = ["{}天".format(i) for i in range(30)]
    days_v1 = [random.randint(1, 30) for _ in range(30)]
    bar = Bar("Bar - datazoom - inside 示例")
    bar.add("", days, days_v1, is_datazoom_show=True,
            datazoom_type='inside', datazoom_range=[10, 25])
    html_content = bar._repr_html_()
    assert "dataZoom" in html_content
    assert ': "inside"' in html_content
    assert ': "slider"' not in html_content
def create_demo_bar(chart_id_demo=None):
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图数据堆叠示例")
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True)
    if chart_id_demo:
        bar._chart_id = chart_id_demo
    return bar
Example #14
0
def test_custom_template_for_chart():
    data = [{
        'name': '衬衫',
        'value': 5
    }, {
        'name': '羊毛衫',
        'value': 20
    }, {
        'name': '雪纺衫',
        'value': 36
    }]

    configure(echarts_template_dir='.')

    online()

    data1 = {'衬衫': '34', '羊毛衫': 45, '雪纺衫': 40}
    names, values = Bar.cast(data)
    names1, values1 = Bar.cast(data1)
    bar = Bar("柱状图数据堆叠示例")
    bar.add("商家A", names, values, is_stack=True)
    bar.add("商家B", names1, values1, is_stack=True)
    bar.render(path='new_version_bar.html')
    with codecs.open('new_version_bar.html', 'r', 'utf-8') as f:
        actual_content = f.read()
        assert "</html>" in actual_content
Example #15
0
def test_numpy_array():
    import numpy as np

    title = "柱状图数据堆叠示例"
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = np.array([5, 20, 36, 10, 75, 90])
    bar = Bar(title)
    bar.add("商家A", attr, v1, is_stack=True)
    html = bar.render_embed()
    json_encoded_title = json.dumps(title)
    assert json_encoded_title in html
def test_chart_properties():
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图-数据堆叠示例", width=900, height=500)
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True)

    eq_(len(bar.chart_id), UUID_HEX_LENGTH)
    eq_(bar.width, 900)
    eq_(bar.height, 500)
    assert ('echarts' in bar.js_dependencies) or \
           ('echarts.min' in bar.js_dependencies)
Example #17
0
def generic_formatter_t_est(**keywords):
    attr = ["Jan", "Feb"]
    v1 = [2.0, 4.9]
    bar = Bar("Bar chart", "precipitation and evaporation one year")
    bar.add(
        "precipitation",
        attr,
        v1,
        mark_line=["average"],
        mark_point=["max", "min"],
        **keywords
    )
    bar.render()
Example #18
0
def test_overlap_bar_line():
    attr = ["A", "B", "C", "D", "E", "F"]
    v1 = [10, 20, 30, 40, 50, 60]
    v2 = [38, 28, 58, 48, 78, 68]
    bar = Bar("Line-Bar 示例")
    bar.add("bar", attr, v1)
    line = Line()
    line.add("line", attr, v2)

    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)
    overlap.render()
Example #19
0
def get_bar(item_name,item_name_list,item_num_list):
    subtitle = "微信公众号:大数据前沿"
    bar = Bar(item_name,page_title = item_name,title_text_size=30,title_pos='center',\
        subtitle = subtitle,subtitle_text_size = 25)
    
    bar.add("", item_name_list, item_num_list,title_pos='center', xaxis_interval=0,xaxis_rotate=27,\
        xaxis_label_textsize = 20,yaxis_label_textsize = 20,yaxis_name_pos='end',yaxis_pos = "%50")
    bar.show_config()

    grid = Grid(width=1300,height= 800)
    grid.add(bar,grid_top = "13%",grid_bottom = "23%",grid_left = "15%",grid_right = "15%")
    out_file_name = './analyse/'+item_name+'.html'
    grid.render(out_file_name)
Example #20
0
def test_overlap_bar_line():
    attr = ['A', 'B', 'C', 'D', 'E', 'F']
    v1 = [10, 20, 30, 40, 50, 60]
    v2 = [38, 28, 58, 48, 78, 68]
    bar = Bar("Line-Bar 示例")
    bar.add("bar", attr, v1)
    line = Line()
    line.add("line", attr, v2)

    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)
    overlap.render()
Example #21
0
def test_bar_waterfall():
    months = ["{}月".format(i) for i in range(1, 8)]
    months_v1 = [0, 100, 200, 300, 400, 220, 250]
    months_v2 = [1000, 800, 600, 500, 450, 400, 300]
    bar = Bar("瀑布图示例")
    bar.add("", months, months_v1, label_color=['rgba(0,0,0,0)'],
            is_stack=True)
    bar.add("月份", months, months_v2, is_label_show=True, is_stack=True,
            label_pos='inside')
    bar.show_config()
    bar.render()
Example #22
0
def test_embed_option():

    # bar_0
    title = "柱状图数据堆叠示例"
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar(title)
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True)
    html = bar.render_embed()
    json_encoded_title = json.dumps(title)
    assert json_encoded_title in html
    assert "<html>" not in html
    assert "<body>" not in html
Example #23
0
def test_bar_datazoom_both():
    days = ["{}天".format(i) for i in range(30)]
    days_v1 = [random.randint(1, 30) for _ in range(30)]
    bar = Bar("Bar - datazoom - both 示例")
    bar.add(
        "",
        days,
        days_v1,
        is_datazoom_show=True,
        datazoom_type="both",
        datazoom_range=[10, 25],
        is_toolbox_show=False,
    )
    html_content = bar._repr_html_()
    assert "dataZoom" in html_content
    assert ': "inside"' in html_content
    assert ': "slider"' in html_content
Example #24
0
def test_overlap_two_yaxis():
    attr = ["{}月".format(i) for i in range(1, 13)]
    v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
    v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
    v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]

    bar = Bar(width=1200, height=600)
    bar.add("蒸发量", attr, v1)
    bar.add("降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250)

    line = Line()
    line.add("平均温度", attr, v3, yaxis_formatter=" °C")

    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line, yaxis_index=1, is_add_yaxis=True)
    overlap.render()
Example #25
0
def test_grid_heatmap_bar():
    data = [[i, j, random.randint(0, 50)]
            for i in range(24) for j in range(7)]
    heatmap = HeatMap("热力图示例", height=700)
    heatmap.add("热力图直角坐标系", X_TIME, Y_WEEK, data, is_visualmap=True,
                visual_top="45%", visual_text_color="#000",
                visual_orient='horizontal')
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", title_top="52%")
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True, legend_top="50%")

    grid = Grid()
    grid.add(heatmap, grid_bottom="60%")
    grid.add(bar, grid_top="60%")
    grid.render()
Example #26
0
def ibar(indicator, new=True, axes=None, 
          legend_on=False, text_on=False, text_color='k',  
          zero_on=False, label=None, *args, **kwargs):
    """绘制indicator曲线
    
    :param Indicator indicator: indicator实例
    :param axes:            指定的坐标轴
    :param new:             pyecharts中无效
    :param legend_on:       是否打开图例
    :param text_on:         是否在左上角显示指标名称及其参数
    :param text_color:      指标名称解释文字的颜色,默认为黑色
    :param zero_on:         是否需要在y=0轴上绘制一条直线
    :param str label:       label显示文字信息,text_on 及 legend_on 为 True 时生效
    :param args:            pylab plot参数
    :param kwargs:          pylab plot参数,如:marker(标记类型)、
                             markerfacecolor(标记颜色)、
                             markeredgecolor(标记的边缘颜色)
    """
    if not indicator:
        print("indicator is None")
        return
    
    if not axes:
        axes = create_figure() if new else gca()
    
    if not label:
        label = "%s %.2f" % (indicator.long_name, indicator[-1])

    x_list = gcf().get_xaxis()
    if x_list is None:
        x_list = [i for i in range(len(indicator))]
        
    y_list = [ '-' if x == constant.null_price else round(x,3) for x in indicator]
    bar = Bar()
        
    style = gcf().get_style(axes, **kwargs)
    bar.add(label, x_list, y_list, 
             yaxis_min=min(indicator),
             is_legend_show=legend_on,
             *args, **style)
    
    axes.add(bar)
        
    gcf().add_axis(axes)
    return gcf()
Example #27
0
def ax_draw_macd2(axes, ref, kdata, n1=12, n2=26, n3=9):
    """绘制MACD
    
    :param axes: 指定的坐标轴
    :param KData kdata: KData
    :param int n1: 指标 MACD 的参数1
    :param int n2: 指标 MACD 的参数2
    :param int n3: 指标 MACD 的参数3
    """
    macd = MACD(CLOSE(kdata), n1, n2, n3)
    bmacd, fmacd, smacd = macd.getResult(0), macd.getResult(1), macd.getResult(2)
    
    text = 'MACD(%s,%s,%s) DIF:%.2f, DEA:%.2f, BAR:%.2f'%(n1,n2,n3,fmacd[-1],smacd[-1],bmacd[-1])
    #axes.text(0.01,0.97, text, horizontalalignment='left', verticalalignment='top', transform=axes.transAxes)
    total = len(kdata)
    x = [i for i in range(total)]
    y = bmacd
    y1,y2,y3 = [y[0]],[y[0]],[y[0]]
    for i in range(1, total):
        if ref[i]-ref[i-1]>0 and y[i]-y[i-1]>0:
            y2.append(y[i])
            y1.append('-')
            y3.append('-')
        elif ref[i]-ref[i-1]<0 and y[i]-y[i-1]<0:
            y3.append(y[i])
            y1.append('-')
            y2.append('-')
        else:
            y1.append(y[i])
            y2.append('-')
            y3.append('-')

    
    style = gcf().get_style(axes)
    bar = Bar(subtitle=text, title_pos='10%', title_top='8%')
    bar.add('1', x, y1, is_stack=True, is_legend_show=False, **style)
    bar.add('2', x, y2, is_stack=True, is_legend_show=False, **style)
    bar.add('3', x, y3, is_stack=True, is_legend_show=False, **style)
    
    axes.add(bar)
    fmacd.plot(axes=axes, line_type='dotted')
    smacd.plot(axes=axes)
    
    gcf().add_axis(axes)
    return gcf()
def draw_citys_pic(csv_file):
    page = Page(csv_file+":评论城市分析")
    info = count_city(csv_file)
    geo = Geo("","Ctipsy原创",title_pos="center", width=1200,height=600, background_color='#404a59', title_color="#fff")
    while True:   # 二次筛选,和pyecharts支持的城市库进行匹配,如果报错则删除该城市对应的统计
        try:
            attr, val = geo.cast(info)
            geo.add("", attr, val, visual_range=[0, 300], visual_text_color="#fff", is_geo_effect_show=False,
                    is_piecewise=True, visual_split_number=6, symbol_size=15, is_visualmap=True)
        except ValueError as e:
            e = str(e)
            e = e.split("No coordinate is specified for ")[1]  # 获取不支持的城市名称
            info.pop(e)
        else:
            break
    info = sorted(info.items(), key=lambda x: x[1], reverse=False)  # list排序
    # print(info)
    info = dict(info)   #list转dict
    # print(info)
    attr, val = [], []
    for key in info:
        attr.append(key)
        val.append(info[key])


    geo1 = Geo("", "评论城市分布", title_pos="center", width=1200, height=600,
              background_color='#404a59', title_color="#fff")
    geo1.add("", attr, val, visual_range=[0, 300], visual_text_color="#fff", is_geo_effect_show=False,
            is_piecewise=True, visual_split_number=10, symbol_size=15, is_visualmap=True, is_more_utils=True)
    #geo1.render(csv_file + "_城市dotmap.html")
    page.add_chart(geo1)
    geo2 = Geo("", "评论来源热力图",title_pos="center", width=1200,height=600, background_color='#404a59', title_color="#fff",)
    geo2.add("", attr, val, type="heatmap", is_visualmap=True, visual_range=[0, 50],visual_text_color='#fff', is_more_utils=True)
    #geo2.render(csv_file+"_城市heatmap.html")  # 取CSV文件名的前8位数
    page.add_chart(geo2)
    bar = Bar("", "评论来源排行", title_pos="center", width=1200, height=600 )
    bar.add("", attr, val, is_visualmap=True, visual_range=[0, 100], visual_text_color='#fff',mark_point=["average"],mark_line=["average"],
            is_more_utils=True, is_label_show=True, is_datazoom_show=True, xaxis_rotate=45)
    #bar.render(csv_file+"_城市评论bar.html")  # 取CSV文件名的前8位数
    page.add_chart(bar)
    pie = Pie("", "评论来源饼图", title_pos="right", width=1200, height=600)
    pie.add("", attr, val, radius=[20, 50], label_text_color=None, is_label_show=True, legend_orient='vertical', is_more_utils=True, legend_pos='left')
    #pie.render(csv_file + "_城市评论Pie.html")  # 取CSV文件名的前8位数
    page.add_chart(pie)
    page.render(csv_file + "_城市评论分析汇总.html")
Example #29
0
def create_three():
    # bar
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图数据堆叠示例")
    bar.add("商家A", CLOTHES, v1, is_stack=True)
    bar.add("商家B", CLOTHES, v2, is_stack=True)

    # scatter3D
    import random
    data = [
        [random.randint(0, 100),
         random.randint(0, 100),
         random.randint(0, 100)] for _ in range(80)
        ]
    scatter3d = Scatter3D("3D 散点图示例", width=1200, height=600)
    scatter3d.add("", data, is_visualmap=True, visual_range_color=RANGE_COLOR)

    return Page.from_charts(bar, scatter3d)
Example #30
0
def test_bar_default(patched):
    fixture = "bar_options.json"
    patched.return_value = "1"
    attr = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
    ]
    v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
    v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
    bar = Bar("Bar chart", "precipitation and evaporation one year")
    bar.add(
        "precipitation",
        attr,
        v1,
        mark_line=["average"],
        mark_point=["max", "min"],
    )
    bar.add(
        "evaporation",
        attr,
        v2,
        mark_line=["average"],
        mark_point=["max", "min"],
    )
    actual_options = json.dumps(
        bar.options, sort_keys=True, indent=4, cls=DefaultJsonEncoder
    )
    expected = get_fixture_content(fixture)
    for a, b in zip(actual_options.split("\n"), expected.split("\n")):
        eq_(a.strip(), b.strip())
def bar_test(a, num):
    X = pd.Series(unique(a)).values
    Y = pd.Series(num.groupby(a).sum()).values
    bar = Bar("香飘飘2019/04到2019/05月各大区经销商分销量")
    bar.add("", X, Y, mark_point=["average"])
    bar.render("E:\\py_data_html\\bar_test.html")
Example #32
0
def test_bar_histogram():
    bar = Bar("直方图示例")
    bar.add("", CLOTHES * 2, clothes_v1 + clothes_v2, bar_category_gap=0)
    bar.render()
Example #33
0
def test_bar_marks():
    bar = Bar("标记线和标记点示例")
    bar.add("商家A", CLOTHES, clothes_v1, mark_point=["average"])
    bar.add("商家B", CLOTHES, clothes_v2, mark_line=["min", "max"])
    assert '"average"' in bar._repr_html_()
Example #34
0
from pyecharts import Bar

bar = Bar("我的第一个图表", "这里是副标题")
bar.use_theme('dark')
bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90])
bar.add("topK", ["张悬", "晚安", "荣幸", "何其", "珍惜", "爱心", "真的", "时候", "拥抱", "知道", "关于", "没有", "首歌", "自己",
                 "喜欢", "侥幸", "拥有", "人生", "失去", "我爱你"], [0, 302, 357, 362, 401, 484, 626, 816, 865, 964, 1056, 1129,
                                                        1185, 1503, 2118, 2618, 2655, 2706, 2758, 2983])
bar.render()
Example #35
0
columns = [
    '肖申克的救赎', '霸王别姬', '阿甘正传', '这个杀手不太冷', '美丽人生', '泰坦尼克号', '千与千寻', '辛德勒的名单',
    '盗梦空间', '忠犬八公的故事', '海上钢琴师', '机器人总动员'
]

data1 = [
    '1723379', '1273976', '1330664', '1524701', '776914', '1267014', '1357107',
    '684518', '1298126', '879080', '1055387', '858246'
]
data2 = [
    '9.7', '9.6', '9.5', '9.4', '9.5', '9.4', '9.3', '9.5', '9.3', '9.3',
    '9.3', '9.3'
]

bar = Bar("TOP 250", "-the movie of top 250 -", width=1500, height=750)

bar.add("people",
        columns,
        data1,
        mark_line=["average"],
        mark_point=["max", "min"])
bar.add("score",
        columns,
        data2,
        mark_line=["average"],
        mark_point=["max", "min"])
bar.render(path="zhuzhuang1.html")
'''
from pyecharts import Pie
attr =["中国香港", "印度", "中国台湾", "瑞典", "英国", "德国", "韩国", "澳大利亚", "伊朗", "美国", "日本", "中国大陆"]
Example #36
0
			date2=str(year1)+'-'+list2[0]+'-'+list2[1]
		else:
			date2=str(year1)+'-'+list2[0]+'-'+list2[1]
		date3 = datetime.datetime.strptime(date2,'%Y-%m-%d').date()
		return date3

def averagenum(num):
    nsum = 0
    for i in range(len(num)):
        nsum += num[i]
    return nsum / len(num)

if __name__ == "__main__":

    i=0
    bar = Bar("南京地铁", "总图",title_pos='left',width=1400, height=700)
    conn = get_conn(DB_FILE_PATH)
    cu = get_cursor(conn)
    fetchall_sql = '''SELECT LineALL FROM NajingMetro'''
    cu.execute(fetchall_sql)
    cnt0 = cu.fetchall()
    cntl0=[]
    for l0 in cnt0:
        cntl0.append(l0[0])

    

    fetchall_sql = '''SELECT DATE FROM NajingMetro'''
    cu.execute(fetchall_sql)
    date1 = cu.fetchall()
    datel1=[]
Example #37
0
'''
echarts-themes-pypkg 提供了 vintage, macarons, infographic, shine 和 roma 主题
# 更换单个主题
bar.use_theme('vintage')
# 更换运行环境所有主题
from pyecharts import configure  置顶
configure(global_theme="dark")
'''

from pyecharts import Bar
import random
bar = Bar('图表标题', '图标副标题')
bar.use_theme('roma')
kind = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
bar.add('商家A',
        kind, [random.randint(10, 100) for _ in range(6)],
        is_more_utils=True)
bar.add('商家B',
        kind, [random.randint(10, 100) for _ in range(6)],
        is_more_utils=True)
bar.add('商家C',
        kind, [random.randint(10, 100) for _ in range(6)],
        is_more_utils=True)
bar.add('商家D',
        kind, [random.randint(10, 100) for _ in range(6)],
        is_more_utils=True)
bar.render()
'''
使用pyecharts-snapshot插件保存图形
如果想直接将图片保存为 png, pdf, gif 格式的文件,可以使用 pyecharts-snapshot
调用 render 方法  bar.render(path='snapshot.png') 文件结尾可以为 svg/jpeg/png/pdf/gif。
Example #38
0
def graphpage(items, startdate, enddate, option, width1, height1):
    page = Page()
    for i in items:  #generate numbers of graphs according to numbers of queries in treewidget
        j = re.split("-", i)
        if len(j) == 3:
            a = generateline(
                j[1], j[2], startdate, enddate, option
            )  #stock number, Type, startdate, enddate, 30 or 15 or days
            if a is None:
                continue
            time = [d[0] for d in a]  #get time from returned dictionary
            if j[2] != "Kline":
                if len(a[0]) == 4 and a[0][2] == "bar":  #for 分笔data
                    overlap = Overlap()
                    form = [e[1] for e in a]
                    bar = Bar(j[0] + "-" + j[2],
                              width=width1 * 10 / 11,
                              height=(height1 * 10 / 11) / len(items))
                    bar.add(j[0] + "-" + j[2],
                            time,
                            form,
                            is_datazoom_show=True,
                            datazoom_type="slider",
                            yaxis_min="dataMin",
                            yaxis_max="dataMax")
                    overlap.add(bar)
                    line = Line(j[0] + "price",
                                width=width1 * 10 / 11,
                                height=(height1 * 10 / 11) / len(items))
                    price = [e[3] for e in a]
                    line.add(j[0] + "price",
                             time,
                             price,
                             is_datazoom_show=True,
                             datazoom_type="slider",
                             yaxis_min="dataMin",
                             yaxis_type="value")
                    overlap.add(line, yaxis_index=1, is_add_yaxis=True)
                    page.add(overlap)

                    #need more statement
                else:
                    form = [e[1] for e in a]  #for not分笔 data
                    line = Line(j[0] + "-" + j[2],
                                width=width1 * 10 / 11,
                                height=(height1 * 10 / 11) / len(items))
                    line.add(j[0] + "-" + j[2],
                             time,
                             form,
                             is_datazoom_show=True,
                             datazoom_type="slider",
                             yaxis_min="dataMin",
                             yaxis_max="dataMax")
                    page.add(line)
            else:
                overlap = Overlap()  #for k线
                close = zip(*a)[2]
                candle = [[x[1], x[2], x[3], x[4]] for x in a]
                candlestick = Kline(j[0] + "-" + j[2],
                                    width=width1 * 10 / 11,
                                    height=(height1 * 10 / 11) / len(items))
                candlestick.add(j[0],
                                time,
                                candle,
                                is_datazoom_show=True,
                                datazoom_type="slider",
                                yaxis_interval=1)
                overlap.add(candlestick)
                if len(close) > 10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(j[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close) > 20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(j[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close) > 30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(j[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)
                page.add(overlap)
        else:
            for k in range(1, len(j) / 3):  #if graphs are combined
                j[3 * k - 1] = re.sub("\n&", "", j[3 * k - 1])
            sizearray = []
            #if j[1] != "Candlestick"
            layout = Overlap()
            for i in xrange(0, len(j), 3):
                array = j[i:i + 3]
                b = generateline(array[1], array[2], startdate, enddate,
                                 option)
                if b is None:
                    continue
                btime = [d[0] for d in b]
                if array[2] != "Kline":

                    if len(b[0]) == 4 and b[0][2] == "bar":
                        form = [e[1] for e in b]
                        bar = Bar(array[0] + "-" + array[2],
                                  width=width1 * 10 / 11,
                                  height=(height1 * 10 / 11) / len(items))
                        bar.add(array[0] + "-" + array[2],
                                btime,
                                form,
                                is_datazoom_show=True,
                                datazoom_type="slider",
                                yaxis_min="dataMin",
                                yaxis_max="dataMax")
                        layout.add(bar)
                        line = Line(array[0] + "price",
                                    width=width1 * 10 / 11,
                                    height=(height1 * 10 / 11) / len(items))
                        price = [e[3] for e in b]
                        line.add(array[0] + "price",
                                 btime,
                                 price,
                                 is_datazoom_show=True,
                                 datazoom_type="slider",
                                 yaxis_min="dataMin",
                                 yaxis_type="value")
                        layout.add(line, yaxis_index=1, is_add_yaxis=True)

                    else:
                        line = Line(array[0] + "-" + array[2],
                                    width=width1 * 10 / 11,
                                    height=(height1 * 10 / 11) / len(items))
                        line.add(array[0] + "-" + array[2],
                                 btime,
                                 b,
                                 is_datazoom_show=True,
                                 yaxis_max="dataMax",
                                 yaxis_min="dataMin",
                                 datazoom_type="slider")
                        layout.add(line)
                else:
                    candle = [[x[1], x[2], x[3], x[4]] for x in b]
                    candlestick = Kline(array[0] + "-" + array[1],
                                        width=width1 * 10 / 11,
                                        height=(height1 * 10 / 11) /
                                        len(items))
                    candlestick.add(array[0],
                                    btime,
                                    candle,
                                    is_datazoom_show=True,
                                    datazoom_type=["slider"])

                    #if i == 0:
                    close = zip(*b)[2]
                    if len(close) > 10:
                        ma10 = calculateMa(close, 10)
                        line4 = Line(title_color="#C0C0C0")
                        line4.add(array[0] + "-" + "MA10", btime, ma10)
                        layout.add(line4)
                    if len(close) > 20:
                        ma20 = calculateMa(close, 20)
                        line5 = Line(title_color="#C0C0C0")
                        line5.add(array[0] + "-" + "MA20", btime, ma20)
                        layout.add(line5)
                    if len(close) > 30:
                        ma30 = calculateMa(close, 30)
                        line6 = Line(title_color="#C0C0C0")
                        line6.add(array[0] + "-" + "MA30", btime, ma30)
                        layout.add(line6)
                    layout.add(candlestick)
            page.add(layout)
    page.render()
Example #39
0
 def getBarImage(self):
     #先获得平均价格的柱状图
     barMeanPrice = Bar("爬取的各品牌手机的平均价格")
     x = []
     y = []
     with open("priceInfo.txt", "r", encoding="utf-8") as f:
         lines = f.readlines()
         for line in lines:
             info = line.split(",")
             x.append(info[0])
             print(info[0])
             y.append(float(info[1]))
             print(float(info[1]))
     kwargs = dict(name="柱形图", x_axis=x, y_axis=y)
     barMeanPrice.add(**kwargs)
     path = self.anaPath + "/平均价格.html"
     barMeanPrice.render(path)
     #接着是差评率
     barBadComment = Bar("各个品牌手机平均差评率(放大10w倍)")
     x = []
     y = []
     with open("BadComment.txt", "r", encoding="utf-8") as f:
         lines = f.readlines()
         for line in lines:
             info = line.split(",")
             x.append(info[0])
             print(info[0])
             y.append(float(info[1]) * 100000)
             print(float(info[1]) * 100000)
     kwargs = dict(name="柱形图", x_axis=x, y_axis=y)
     barBadComment.add(**kwargs)
     path = self.anaPath + "/平均差评率.html"
     barBadComment.render(path)
Example #40
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from pyecharts import WordCloud
import time
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
from pyecharts import Bar

bar = Bar("我的第一个图表", "这里是副标题")
bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90],
        is_more_utils=True)
bar.show_config()
bar.render()


class Visualizaion:
    def __init__(self):
        pass

    def wordcloud():
        wc = WordCloud("绘制词云", width=1000, height=620)
        name = [
            'Sam S Club', 'Macys', 'Amy Schumer', 'Jurassic World',
            'Charter Communications', 'Chick Fil A', 'Planet Fitness',
            'Pitch Perfect', 'Express', 'Home', 'Johnny Depp', 'Lena Dunham',
            'Lewis Hamilton', 'KXAN', 'Mary Ellen Mark', 'Farrah Abraham',
            'Rita Ora', 'Serena Williams', 'NCAA baseball tournament',
            'Point Break'
Example #41
0
def drawecharts(namelist, numlist):
    '''
	title -> str
	主标题文本,支持 \n 换行,默认为空

	subtitle -> str
	副标题文本,支持 \n 换行,默认为 空

	width -> int
	画布宽度,默认为 800(px)

	height -> int
	画布高度,默认为 400(px)

	title_color -> str
	主标题文本颜色,默认为 ‘#000’

	subtitle_color -> str

	副标题文本颜色,默认为 ‘#aaa’

	background_color -> str

	画布背景颜色,默认为 ‘#fff’

	page_title -> str
	指定生成的 html 文件中 <title> 标签的值。默认为’Echarts’

	renderer -> str
	指定使用渲染方式,有 ‘svg’ 和 ‘canvas’ 可选,默认为 ‘canvas’。
	'''

    bar = Bar("小说数量统计",
              "2019-6-28",
              title_color='red',
              title_pos='right',
              width=1200,
              height=600,
              background_color='#fff')
    '''
	is_random -> bool
	是否随机排列颜色列表,默认为 False

	label_color -> list
	自定义标签颜色。全局颜色列表,所有图表的图例颜色均在这里修改。如 Bar 的柱状颜色,Line 的线条颜色等等。

	is_label_show -> bool
	是否正常显示标签,默认不显示。标签即各点的数据项信息

	label_pos -> str
	标签的位置,Bar 图默认为’top’。有’top’, ‘left’, ‘right’, ‘bottom’, ‘inside’,’outside’可选

	label_text_color -> str
	标签字体颜色,默认为 “#000”

	label_text_size -> int
	标签字体大小,默认为 12

	is_random -> bool
	是否随机排列颜色列表,默认为 False

	label_formatter -> function
	'''
    bar.add("下载数量",
            namelist,
            numlist,
            is_more_utils=True,
            is_label_show=True,
            is_datazoom_show=False,
            legend_pos='left',
            is_convert=False,
            is_random=True)

    # 其他主题:vintage,macarons,infographic,shine,roma
    bar.use_theme("vintage")  #单个主题更换
    #  from pyecharts import configure    #全局主题更换
    #  configure(global_theme='vintage')  #全局主题更换
    bar.show_config()
    bar.render()
Example #42
0
def create_charts():
    page = Page()

    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=800, width=WIDTH)
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True)
    line = Line("折线图示例", title_top="50%")
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温",
             attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"],
             mark_line=["average"])
    line.add("最低气温",
             attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"],
             mark_line=["average"],
             legend_top="50%")
    chart = Grid()
    chart.add(bar, grid_bottom="60%")
    chart.add(line, grid_top="60%")
    page.add(chart)

    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    scatter = Scatter("散点图示例", width=WIDTH, title_pos="55%")
    scatter.add("scatter", v1, v2, legend_pos="70%")
    es = EffectScatter("动态散点图示例")
    es.add("effectScatter", [11, 11, 15, 13, 12, 13, 10],
           [1, -2, 2, 5, 3, 2, 0],
           effect_scale=6,
           legend_pos="20%")
    chart = Grid()
    chart.add(scatter, grid_left="60%")
    chart.add(es, grid_right="60%")
    page.add(chart)

    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", height=740, width=WIDTH, title_pos="65%")
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True, legend_pos="80%")
    line = Line("折线图示例")
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温",
             attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"],
             mark_line=["average"])
    line.add("最低气温",
             attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"],
             mark_line=["average"],
             legend_pos="20%")
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    scatter = Scatter("散点图示例", title_top="50%", title_pos="65%")
    scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%")
    es = EffectScatter("动态散点图示例", title_top="50%")
    es.add("es", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0],
           effect_scale=6,
           legend_top="50%",
           legend_pos="20%")
    chart = Grid()
    chart.add(bar, grid_bottom="60%", grid_left="60%")
    chart.add(line, grid_bottom="60%", grid_right="60%")
    chart.add(scatter, grid_top="60%", grid_left="60%")
    chart.add(es, grid_top="60%", grid_right="60%")
    page.add(chart)

    line = Line("折线图示例", width=WIDTH)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温",
             attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"],
             mark_line=["average"])
    line.add("最低气温",
             attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"],
             mark_line=["average"],
             legend_pos="20%")
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [11, 12, 13, 10, 10, 10]
    pie = Pie("饼图示例", title_pos="55%")
    pie.add("",
            attr,
            v1,
            radius=[45, 65],
            center=[70, 50],
            legend_pos="85%",
            legend_orient='vertical')
    chart = Grid()
    chart.add(line, grid_right="55%")
    chart.add(pie, grid_left="60%")
    page.add(chart)

    line = Line("折线图示例", width=WIDTH)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温",
             attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"],
             mark_line=["average"])
    line.add("最低气温",
             attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"],
             mark_line=["average"],
             legend_pos="20%")
    v1 = [[2320.26, 2320.26, 2287.3,
           2362.94], [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58,
           2440.38], [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例", title_pos="60%")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)],
              v1,
              legend_pos="80%")
    chart = Grid()
    chart.add(line, grid_right="60%")
    chart.add(kline, grid_left="55%")
    page.add(chart)

    data = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)]
    heatmap = HeatMap("热力图示例", width=WIDTH, height=700)
    heatmap.add("热力图直角坐标系",
                X_TIME,
                Y_WEEK,
                data,
                is_visualmap=True,
                visual_top="45%",
                visual_text_color="#000",
                visual_orient='horizontal')
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图示例", title_top="52%")
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True, legend_top="50%")
    chart = Grid()
    chart.add(heatmap, grid_bottom="60%")
    chart.add(bar, grid_top="60%")
    page.add(chart)

    line = Line("折线图示例", width=WIDTH, height=700)
    attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    line.add("最高气温",
             attr, [11, 11, 15, 13, 12, 13, 10],
             mark_point=["max", "min"],
             mark_line=["average"])
    line.add("最低气温",
             attr, [1, -2, 2, 5, 3, 2, 0],
             mark_point=["max", "min"],
             legend_top="50%",
             mark_line=["average"],
             is_datazoom_show=True,
             datazoom_xaxis_index=[0, 1])

    v1 = [[2320.26, 2320.26, 2287.3,
           2362.94], [2300, 2291.3, 2288.26, 2308.38],
          [2295.35, 2346.5, 2295.35, 2345.92],
          [2347.22, 2358.98, 2337.35, 2363.8],
          [2360.75, 2382.48, 2347.89, 2383.76],
          [2383.43, 2385.42, 2371.23, 2391.82],
          [2377.41, 2419.02, 2369.57, 2421.15],
          [2425.92, 2428.15, 2417.58,
           2440.38], [2411, 2433.13, 2403.3, 2437.42],
          [2432.68, 2334.48, 2427.7, 2441.73],
          [2430.69, 2418.53, 2394.22, 2433.89],
          [2416.62, 2432.4, 2414.4, 2443.03],
          [2441.91, 2421.56, 2418.43, 2444.8],
          [2420.26, 2382.91, 2373.53, 2427.07],
          [2383.49, 2397.18, 2370.61, 2397.94],
          [2378.82, 2325.95, 2309.17, 2378.82],
          [2322.94, 2314.16, 2308.76, 2330.88],
          [2320.62, 2325.82, 2315.01, 2338.78],
          [2313.74, 2293.34, 2289.89, 2340.71],
          [2297.77, 2313.22, 2292.03, 2324.63],
          [2322.32, 2365.59, 2308.92, 2366.16],
          [2364.54, 2359.51, 2330.86, 2369.65],
          [2332.08, 2273.4, 2259.25, 2333.54],
          [2274.81, 2326.31, 2270.1, 2328.14],
          [2333.61, 2347.18, 2321.6, 2351.44],
          [2340.44, 2324.29, 2304.27, 2352.02],
          [2326.42, 2318.61, 2314.59, 2333.67],
          [2314.68, 2310.59, 2296.58, 2320.96],
          [2309.16, 2286.6, 2264.83, 2333.29],
          [2282.17, 2263.97, 2253.25, 2286.33],
          [2255.77, 2270.28, 2253.31, 2276.22]]
    kline = Kline("K 线图示例", title_top="50%")
    kline.add("日K", ["2017/7/{}".format(i + 1) for i in range(31)],
              v1,
              is_datazoom_show=True)

    chart = Grid()
    chart.add(line, grid_top="60%")
    chart.add(kline, grid_bottom="60%")
    page.add(chart)

    attr = ['{}天'.format(i) for i in range(1, 31)]
    line_top = Line("折线图示例", width=WIDTH, height=700)
    line_top.add("最高气温",
                 attr, [random.randint(20, 100) for i in range(30)],
                 mark_point=["max", "min"],
                 mark_line=["average"],
                 legend_pos='38%')
    line_bottom = Line()
    line_bottom.add("最低气温",
                    attr, [random.randint(20, 100) for i in range(30)],
                    mark_point=["max", "min"],
                    mark_line=["average"],
                    is_yaxis_inverse=True,
                    xaxis_pos='top')
    chart = Grid()
    chart.add(line_top, grid_bottom='60%')
    chart.add(line_bottom, grid_top='50%')
    page.add(chart)

    attr = ["{}月".format(i) for i in range(1, 13)]
    v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
    v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
    v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
    bar = Bar("Overlap+Grid 示例", title_pos="40%", width=1100, height=600)
    bar.add("蒸发量", attr, v1)
    bar.add("降水量",
            attr,
            v2,
            yaxis_formatter=" ml",
            yaxis_max=250,
            legend_pos="85%",
            legend_orient="vertical",
            legend_top="45%")
    line = Line()
    line.add("平均温度", attr, v3, yaxis_formatter=" °C")
    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line, is_add_yaxis=True, yaxis_index=1)

    chart = Grid()
    chart.add(overlap, grid_right='20%')
    page.add(chart)

    return page
Example #43
0
    "Wednesday",
    "Tuesday",
    "Monday",
    "Sunday",
]
data = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)]
heatmap = HeatMap("热力图示例")
heatmap.add(
    "热力图直角坐标系",
    x_axis,
    y_axis,
    data,
    is_visualmap=True,
    visual_top="45%",
    visual_text_color="#000",
    visual_orient="horizontal",
)
attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [5, 20, 36, 10, 75, 90]
v2 = [10, 25, 8, 60, 20, 80]
bar = Bar("柱状图示例", title_top="52%")
bar.add("商家A", attr, v1, is_stack=True)
bar.add("商家B", attr, v2, is_stack=True, legend_top="50%")

grid = Grid(height=700)
grid.add(heatmap, grid_bottom="60%")
grid.add(bar, grid_top="60%")

page.add(grid)
page.render('./grid01.html')
Example #44
0
from django.test import TestCase

# Create your tests here.
from pyecharts import Bar

attr = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
    "Nov", "Dec"
]
v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
bar = Bar("Bar chart", "precipitation and evaporation one year")
bar.add("precipitation",
        attr,
        v1,
        mark_line=["average"],
        mark_point=["max", "min"])
bar.add("evaporation",
        attr,
        v2,
        mark_line=["average"],
        mark_point=["max", "min"])
bar.render()
Example #45
0
def index():
    try:
        whitelist = []
        Key = "op_alarm_load_whitelist"
        if RC_CLUSTER.exists(Key):
            whitelist = RC_CLUSTER.smembers(Key)
        td = time.strftime("%Y-%m-%d", time.localtime())
        td_1 = datetime.datetime.now() - datetime.timedelta(days=1)
        td_1 = td_1.strftime("%Y-%m-%d")
        td_7 = datetime.datetime.now() - datetime.timedelta(days=7)
        td_7 = td_7.strftime("%Y-%m-%d")
        TM = time.strftime('%M', time.localtime())
        BUSIS = []
        #业务信息展示
        try:
            Key = 'op_k8s_ingress_log'
            k8s_domains_key = 'op_k8s_domains_%s' % td
            total_key = 'op_totals_alarms_tmp'
            if RC.exists(k8s_domains_key):
                try:
                    line = Line("容器平台业务RPS统计",
                                width='105%',
                                height=250,
                                title_pos='center',
                                title_text_size=12)
                    for domain in RC.smembers(k8s_domains_key):
                        if RC.exists('%s_%s_%s' % (Key, domain, td)):
                            vals = RC.hgetall('%s_%s_%s' % (Key, domain, td))
                            vals = sorted(vals.items(),
                                          key=lambda item: item[0])
                            attrs = [val[0] for val in vals[-10:]]
                            vals = [
                                int(int(val[1]) / 60) for val in vals[-10:]
                            ]
                            line.add(domain,
                                     attrs,
                                     vals,
                                     is_label_show=True,
                                     is_toolbox_show=False,
                                     legend_pos='65%',
                                     xaxis_interval=0,
                                     is_fill=True,
                                     area_opacity=0.3,
                                     is_smooth=True)
                except Exception as e:
                    logging.error(e)
            else:
                for i in range(7):
                    data_now = datetime.datetime.now() - datetime.timedelta(
                        days=i)
                    dd = data_now.strftime('%Y-%m-%d')
                    alarm_count_key = '%s_%s' % ('op_business_alarm_count', dd)
                    if RC_CLUSTER.exists(alarm_count_key):
                        vals = RC_CLUSTER.hgetall(alarm_count_key)
                        vals = sorted(vals.items(),
                                      key=lambda item: int(item[1]))
                        for val in vals:
                            RC_CLUSTER.hincrby(total_key, dd, val[1])
                line = Line("业务监控报警近期统计",
                            width='105%',
                            height=250,
                            title_pos='center',
                            title_text_size=12)
                if RC_CLUSTER.exists(total_key):
                    vals = RC_CLUSTER.hgetall(total_key)
                    vals = sorted(vals.items(),
                                  key=lambda item: item[0],
                                  reverse=True)
                    RC_CLUSTER.delete(total_key)
                    attrs = [val[0] for val in vals]
                    vals = [int(val[1]) for val in vals]
                    line.add("",
                             attrs,
                             vals,
                             is_label_show=True,
                             is_toolbox_show=False,
                             is_legend_show=False,
                             xaxis_interval=0,
                             is_fill=True,
                             area_opacity=0.3,
                             is_smooth=True)
            bar = Bar("线上业务实时PV统计",
                      width='105%',
                      height=250,
                      title_pos='center',
                      title_text_size=12)
            busi_vals = RC_CLUSTER.hgetall('op_business_pv_%s' % td)
            if busi_vals:
                busi_vals = sorted(busi_vals.items(),
                                   key=lambda item: int(float(item[1])),
                                   reverse=True)
                bar_vals = [val[0] for val in busi_vals[:8]]
                bar_counts = [
                    float('%.4f' % (float(val[1]) / 100000000))
                    for val in busi_vals[:8]
                ]
                bar.add("",
                        bar_vals,
                        bar_counts,
                        is_label_show=True,
                        is_toolbox_show=False,
                        legend_orient='vertical',
                        legend_pos='right',
                        xaxis_interval=0,
                        yaxis_formatter='亿')
            BUSIS.extend((bar, line))
        except Exception as e:
            logging.error(e)
        #网站并发访问展示
        try:
            NEW_DATA = [
                eval(v) for v in RC.lrange('internet_access_%s' % td, 0, -1)
            ]
            attr = [DATA[0] for DATA in NEW_DATA]
            vals = [int(int(DATA[1]) / 60) for DATA in NEW_DATA]
            line = Line('墨迹线上业务RPS统计',
                        title_pos='center',
                        title_text_size=12,
                        width='109%',
                        height='250px')
            line.add("今天",
                     attr,
                     vals,
                     is_toolbox_show=False,
                     is_smooth=True,
                     mark_point=["max", "min"],
                     mark_point_symbolsize=80,
                     is_datazoom_show=True,
                     datazoom_range=[v for v in range(100, 10)],
                     datazoom_type='both',
                     legend_pos='70%')
            if RC.exists('internet_access_%s' % td_1):
                OLD_DATA = [
                    eval(v)
                    for v in RC.lrange('internet_access_%s' % td_1, 0, -1)
                ]
                OLD_DATA = [val for val in OLD_DATA if val[0] in attr]
                old_attr = [DATA[0] for DATA in OLD_DATA]
                old_vals = [int(int(DATA[1]) / 60) for DATA in OLD_DATA]
                if attr and vals:
                    line.add("昨天",
                             old_attr,
                             old_vals,
                             is_toolbox_show=False,
                             is_smooth=True,
                             mark_point=["max", "min"],
                             mark_point_symbolsize=80,
                             is_datazoom_show=True,
                             datazoom_range=[v for v in range(100, 10)],
                             datazoom_type='both',
                             legend_pos='70%')
            if RC.exists('internet_access_%s' % td_7):
                OLD_DATA = [
                    eval(v)
                    for v in RC.lrange('internet_access_%s' % td_7, 0, -1)
                ]
                OLD_DATA = [val for val in OLD_DATA if val[0] in attr]
                old_attr = [DATA[0] for DATA in OLD_DATA]
                old_vals = [int(int(DATA[1]) / 60) for DATA in OLD_DATA]
                if attr and vals:
                    line.add("上周",
                             old_attr,
                             old_vals,
                             is_toolbox_show=False,
                             is_smooth=True,
                             mark_point=["max", "min"],
                             mark_point_symbolsize=80,
                             is_datazoom_show=True,
                             datazoom_range=[v for v in range(100, 10)],
                             datazoom_type='both',
                             legend_pos='70%')
        except Exception as e:
            logging.error(e)
        #监控数据展示
        try:
            tm = datetime.datetime.now() - datetime.timedelta(minutes=1)
            tm = tm.strftime('%H:%M')
            z_triggers = RC.hgetall('zabbix_triggers_%s' % tm)
            if z_triggers:
                z_triggers = [[t, z_triggers[t]] for t in z_triggers]
        except Exception as e:
            logging.error(e)
        #服务器预警信息
        try:
            z_infos = defaultdict()
            dict_load = None
            dict_openfile = None
            if RC_CLUSTER.exists('op_zabbix_server_load_top'):
                dict_load = eval(RC_CLUSTER.get('op_zabbix_server_load_top'))
            if RC_CLUSTER.exists('op_zabbix_server_openfile_top'):
                dict_openfile = eval(
                    RC_CLUSTER.get('op_zabbix_server_openfile_top'))
            if dict_load:
                z_infos['cpu_load'] = dict_load
            if dict_openfile:
                z_infos['openfile'] = dict_openfile
        except Exception as e:
            logging.error(e)
        # 获取问题服务器列表
        fault_servers = defaultdict()
        try:
            for key in ('ssh_login_fault_%s' % td, 'ssh_port_fault_%s' % td):
                if RC.exists(key):
                    fault_vals = RC.hgetall(key)
                    if fault_vals:
                        fault_servers[key] = zip(
                            [fault_vals[val] for val in fault_vals],
                            [val.split(':')[0] for val in fault_vals],
                            [val.split(':')[1] for val in fault_vals])
        except Exception as e:
            logging.error(e)
        app_resp = make_response(
            render_template('index.html',
                            line=line,
                            tm=TM,
                            z_triggers=z_triggers,
                            z_infos=z_infos,
                            fault_servers=fault_servers,
                            BUSIS=BUSIS,
                            whitelist=whitelist))
        app_resp.set_cookie('secret_key',
                            tools.Produce(length=8, chars=string.digits),
                            path='/')
        return app_resp
    except Exception as e:
        logging.error(e)
        flash('获取数据错误!', "error")
        return render_template('Message.html')
    dh.append(int(item['heal']))
#图表生成
map = Map('福建省2019-nCoV疫情(' + yesterday.strftime("%Y-%m-%d") + ')',
          '注:省卫健委每日11时发布前一天疫情通报\n更新时间:' + lastUpdate,
          width=1024,
          height=768)
map.add("确诊病例",
        fjcity,
        confirm,
        maptype='福建',
        visual_range=[0, max(confirm)],
        is_visualmap=True,
        visual_text_color='#000',
        is_label_show=True)

bar = Bar()
bar.add('确诊病例', fjcity, confirm, is_label_show=True)
bar.add('新增确诊病例', fjcity, todayConfirm, is_label_show=True)

l = len(dates)
line = Line('附:全国疫情', '最近7天数据(来源:腾讯新闻疫情动态)')
line.add('新增确诊', dates[l - 7:l], dc[l - 7:l], is_label_show=True)
line.add('新增疑似', dates[l - 7:l], ds[l - 7:l], is_label_show=True)
#line.add('新增死亡',dates[l-7:l],dd[l-7:l],is_label_show=True)
line.add('新增治愈', dates[l - 7:l], dh[l - 7:l], is_label_show=True)
#页面生成
page = Page()  #'福建省2019-nCoV疫情'
print('type(page)', type(page))
page.add(map)
page.add(bar)
page.add(line)
Example #47
0
                       user='******',
                       password='******',
                       port=3306,
                       db='maoyan',
                       charset='utf8mb4')
cursor = conn.cursor()
sql = "select * from films"
db = pd.read_sql(sql, conn)
list1 = []
for i in db['country']:
    place = i.split(',')[0]
    list1.append(place)
db['location'] = list1

place_message = db.groupby(['location'])
place_com = place_message['location'].agg(['count'])
place_com.reset_index(inplace=True)
place_com_last = place_com.sort_index()
dom = place_com_last.sort_values('count', ascending=False)[0:10]

attr = dom['location']
v1 = dom['count']

bar = Bar("2018年各国家电影数量TOP10",
          title_pos='center',
          title_top='18',
          width=800,
          height=400)
bar.add("", attr, v1, is_stack=True, is_label_show=True)
bar.render("2018年各国家电影数量TOP10.html")
Example #48
0
def RowAnalyse(chatrooms_single,
               filename="Row_ana",
               start_time="1970-01-02",
               end_time=""):
    '''
    统计聊天条数分布
    个人
    '''
    chatrooms = chatrooms_single
    RowNum = {}
    for chatroom in chatrooms:
        RowNum[chatroom] = basicTool.GetRowNum(chatroom,
                                               start_time=start_time,
                                               end_time=end_time)
    # sorted_list = sorted(RowNum.items(), key=operator.itemgetter(1),reverse=True)
    # f = open("../../rows.txt","w+",encoding="utf-8")
    # for i in sorted_list:
    #     f.write(i[0]+","+str(basicTool.GetWXID(i[0]))+","+str(i[1])+"\n")
    # f.close()
    sorted_list = sorted(RowNum.items(),
                         key=operator.itemgetter(1),
                         reverse=True)

    #x_axis = list(range(len(sorted_list))) #不显示姓名时用这个
    x_axis = [
        str(i + 1) + "," + basicTool.GetName(sorted_list[i][0])
        for i in range(len(sorted_list))
    ]
    y_axis = [i[1] for i in sorted_list]
    bar_top = Bar("条数统计", title_pos="10%")

    def label_formatter(params):
        return params.split(",")[0]

    bar_top.add(
        "",
        x_axis,
        y_axis,
        # xaxis_interval=0,
        # xaxis_rotate = 30,
        xaxis_formatter=label_formatter,
        yaxis_name="条数",
        is_xaxislabel_align=True,
        is_datazoom_show=True,
        datazoom_range=[0, 100])

    # bar_bottom = Bar("条数统计-对数坐标", title_top="55%",title_pos="10%")
    # bar_bottom.add(
    #     "",
    #     x_axis,
    #     y_axis,
    #     # xaxis_interval=0,
    #     # xaxis_rotate = 30,
    #     xaxis_formatter = label_formatter,
    #     yaxis_name="条数",
    #     yaxis_type='log',
    #     is_xaxislabel_align=True
    # )
    # grid = Grid(width=1920, height=1080)
    # grid.add(bar_top, grid_bottom="60%")
    # grid.add(bar_bottom, grid_top="60%")
    bar_top.render(path=filename + ".html")
Example #49
0
pie.add(
    "",
    attr,
    v1,
    radius=[40, 75],
    label_text_color=None,
    is_label_show=True,
    legend_orient="vertical",
    legend_pos="left",
)
pie.render(r'E:\vscode_code\GitHub项目\爬虫+数据分析\高德地图\服务数量统计.html')

#柱状图
attr = list(typ2.index)[:10]
v1 = list(typ2)[:10]
bar = Bar("")
bar.add("",
        attr,
        v1,
        xaxis_interval=0,
        xaxis_rotate=20,
        xaxis_margin=8,
        is_label_show=True)
bar.render(r'E:\vscode_code\GitHub项目\爬虫+数据分析\高德地图\中外餐厅类型数量.html')

#地图
m = folium.Map(location=[28.12, 112.59])
m.save(r'E:\vscode_code\GitHub项目\爬虫+数据分析\高德地图\餐厅位置.html')

#热力图
df1 = data[data['typ1'] == '餐饮服务']
Example #50
0
def PL_draw_echarts(PL_df, PL_slices):
    # 初始化一个画图的页面.每一种信号画一张图片
    PL_page = Page()
    PL_columns = PL_df.columns.values.tolist()
    # 所有统计的信号种类
    PL_signal_items = list(set(PL_df['signal_name'].tolist()))
    PL_signal_items.sort()

    # 所有的N[第n个bar]
    PL_bar_nos = []
    for PL_col in PL_columns:
        if re.match('chg_pct_', PL_col):
            # 获取当前统计的是第几根bar的收益
            PL_bar_nos.append(PL_col.replace('chg_pct_', ''))

    for PL_sig in PL_signal_items:
        # 获取一种信号在M个bar内的收益统计
        PL_bar = Bar(PL_sig + "收益分布", title_text_size=14, width='100%')

        PL_sdf = PL_df[(PL_df['signal_name'] == PL_sig)]
        if PL_sdf.empty:
            continue

        # 划分收益区间,从0开始往正负两端划分收益区间
        # 计算每个收益区间的大小
        PL_max_profit = 0
        PL_min_profit = 0
        for PL_no in PL_bar_nos:
            PL_pcol = 'chg_pct_' + PL_no
            PL_profits = PL_sdf[PL_pcol].tolist()
            PL_max_profit = max(max(PL_profits), PL_max_profit)
            PL_min_profit = min(min(PL_profits), PL_min_profit)
        PL_intervals = []
        if PL_min_profit < 0:
            PL_unit = round(
                max(PL_max_profit, abs(PL_min_profit)) / PL_slices, 4)
            # 先划分小于0的区间
            for i in range(0, int(math.ceil(abs(PL_min_profit) / PL_unit))):
                PL_intervals.append(
                    [round(-(i + 1) * PL_unit, 4),
                     round(-i * PL_unit, 4)])
            PL_intervals.reverse()
        else:
            PL_unit = PL_max_profit / PL_slices

        for i in range(0, int(math.ceil(abs(PL_max_profit) / PL_unit))):
            PL_intervals.append([i * PL_unit, (i + 1) * PL_unit])

        # 显示收益区间之前先格式化成百分比。
        PL_format_intervals = [
            '%.2f%%~%.2f%%' % (i[0] * 100, i[1] * 100) for i in PL_intervals
        ]

        for PL_no in PL_bar_nos:
            # 计算第M个bar收益,落在某一个收益区间的概率
            PL_win_ratios = []
            PL_pcol = 'chg_pct_' + PL_no
            for PL_interval in PL_intervals:
                # 统计在收益落在某个收益区间的概率
                PL_conf = (PL_sdf[PL_pcol] > PL_interval[0]) & (
                    PL_sdf[PL_pcol] <= PL_interval[1])
                # 避免int类型直接除之后返回的还是int,这里*1.0
                PL_win_ratios.append(
                    round(len(PL_sdf[PL_conf]) / (len(PL_sdf) * 1.0), 2))
            PL_bar.add(
                "第%s个bar" % PL_no,
                PL_format_intervals,
                PL_win_ratios,
                xaxis_name='收益区间',
                xaxis_name_pos='end',
                xaxis_name_size=12,
                xaxis_label_textsize=12,
                xaxis_interval=1,
                xaxis_rotate=45,
                yaxis_name='概率',
                yaxis_name_pos='end',
                yaxis_name_size=12,
                yaxis_label_textsize=12,
                is_splitline_show=False,
                # 默认为 X 轴,横向
                is_datazoom_show=True,
                datazoom_type="both",
                datazoom_range=[40, 60],
                # 额外的 dataZoom 控制条,纵向
                # is_datazoom_extra_show=True,
                # datazoom_extra_type="slider",
                # datazoom_extra_range=[10, 25],
                # is_toolbox_show=False,
            )
        PL_grid = Grid(width='100%')
        PL_grid.add(PL_bar, grid_bottom=120)
        PL_page.add(PL_grid)

    PL_page.render()
Example #51
0
"""
from pyecharts import Bar
import pandas as pd

df = pd.read_csv('sg_articles.csv', header=None, names=["title", "article", "name", "date"])

list1 = []
for j in df['date']:
    # 获取文章发布年份
    time = j.split('-')[0]
    list1.append(time)
df['year'] = list1

# 选取发布时间为2018年的文章,并对其统计
df = df.loc[df['year'] == '2018']
place_message = df.groupby(['name'])
place_com = place_message['name'].agg(['count'])
place_com.reset_index(inplace=True)
place_com_last = place_com.sort_index()
dom = place_com_last.sort_values('count', ascending=False)[0:10]

attr = dom['name']
v1 = dom['count']
bar = Bar("微信文章发布数量TOP10", title_pos='center', title_top='18', width=800, height=400)
bar.add("", attr, v1, is_convert=True, xaxis_min=10, yaxis_rotate=30, yaxis_label_textsize=10,
        is_yaxis_boundarygap=True, yaxis_interval=0, is_label_show=True, is_legend_show=False,
        label_pos='right', is_yaxis_inverse=True, is_splitline_show=False)
bar.render("微信文章发布数量TOP10.html")


Example #52
0
def create_simple_bar():
    bar = Bar("我的第一个图表", "这里是副标题")
    bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
            [5, 20, 36, 10, 75, 90])
    return bar
Example #53
0
from pyecharts import Bar, Line, Scatter, EffectScatter, Grid
# ************************************************************************************
attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [5, 20, 36, 10, 75, 90]
v2 = [10, 25, 8, 60, 20, 80]
bar = Bar("柱状图示例", title_pos="65%")
bar.add("商家A", attr, v1, is_stack=True)
bar.add("商家B", attr, v2, is_stack=True, legend_pos="80%")
# ************************************************************************************
line = Line("折线图示例")
attr = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
line.add(
    "最高气温",
    attr,
    [11, 11, 15, 13, 12, 13, 10],
    mark_point=["max", "min"],
    mark_line=["average"],
)
line.add(
    "最低气温",
    attr,
    [1, -2, 2, 5, 3, 2, 0],
    mark_point=["max", "min"],
    mark_line=["average"],
    legend_pos="20%",
)
# ************************************************************************************
v1 = [5, 20, 36, 10, 75, 90]
v2 = [10, 25, 8, 60, 20, 80]
scatter = Scatter("散点图示例", title_top="50%", title_pos="65%")
scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%")
Example #54
0
tsum = []
for w in namelist:
    i = 0
    s_list = []
    for t in a.title:
        if w in t:
            #            s_list.append(1)    #可显示出现频数
            s_list.append(a.sale[i])
        i += 1
    tsum.append(sum(s_list))

df_w_sum = pd.DataFrame({'tsum': tsum})
name = pd.DataFrame({'word': namelist})
df_sum = pd.concat([name, df_w_sum], axis=1, ignore_index=True)
df_sum.columns = ['word', 'w_s_sum']
bar = Bar('标题与销售额')
bar.add('总', df_sum['word'], df_sum['w_s_sum'], is_stack=True, xaxis_rotate=30)
bar.render('标题和销售额.html')

#%%
##2.标题名和售价分布
m_price = []
for w in namelist:
    i = 0
    lst = []
    for t in a.title:
        if w in t:
            lst.append(a.price[i])
        i += 1
    m_price.append(round(np.mean(lst), 2))
Example #55
0
    #post请求得到的是一个json数据,所以要用json.loads()解析一下数据
    data = json.loads(html.text)
    remark = []
    for hotcomment in data['hotComments']:
        items = {
            'nickName': hotcomment['user']['nickname'],
            'content': hotcomment['content'],
            'likedCount': hotcomment['likedCount']
        }
        remark.append(items)
    nick_name = [content['nickName'] for content in remark]
    content_list = [content['content'] for content in remark]
    liked_count = [content['likedCount'] for content in remark]

#使用pyecharts 模块生成一个图表
bar = Bar("热评中点赞数示例图")
#.add()主要方法,用于添加图表的数据和设置各种配置项
bar.add("点赞数",
        nick_name,
        liked_count,
        is_stack=True,
        mark_line=["min", "max"],
        mark_point=["average"])
#.render()默认将会在根目录下生成一个 render.html 的文件,支持 path 参数,设置文件保存位置,如 render(r"e:my_first_chart.html"),文件用浏览器打开。
bar.render()

#使用wordcloud模块绘制词云图,并用matplotlib可视化

content_text = " ".join(
    content_list)  #str.join(squence) 方法用于将序列str中的元素以指定的字符squence连接生成一个新的字符串
def all_bumen_bar(start=None, end=None):
    print(time.time())
    try:
        starttime = datetime.datetime.strptime(start, '%Y-%m-%d')
    except:
        starttime = time.strftime("%Y-%m-%d 00:00:00")
        starttime = datetime.datetime.strptime(starttime, '%Y-%m-%d 00:00:00')
    try:
        endtime = datetime.datetime.strptime(
            end, '%Y-%m-%d') + datetime.timedelta(days=1)
    except:
        endtime = time.strftime("%Y-%m-%d 23:59:59")
        endtime = datetime.datetime.strptime(endtime, '%Y-%m-%d 23:59:59')

    print(starttime, endtime)
    zx_piaohao_list = zx_piaohaotongji.objects.filter(
        creationtime__gte=starttime, creationtime__lte=endtime)
    rz_queue_list = rz_queuehist.objects.filter(hjtime__gte=starttime,
                                                hjtime__lte=endtime)
    ga_queue_list = ga_queuehist.objects.filter(ssd__gte=starttime,
                                                ssd__lte=endtime)
    gs_queue_list = gs_queuehist.objects.filter(endtime__gte=starttime,
                                                endtime__lte=endtime)

    print(zx_piaohao_list)
    bumen_name_list = []
    bumen_count_list = []

    bumen_name_list.append('综合服务中心')
    bumen_count_list.append(zx_piaohao_list.count())
    bumen_name_list.append('人力资源局')
    bumen_count_list.append(rz_queue_list.count())
    bumen_name_list.append('公安分局')
    bumen_count_list.append(ga_queue_list.count())
    bumen_name_list.append('工商分局')
    bumen_count_list.append(gs_queue_list.count())

    bumen_count_all = zx_piaohao_list.count() + rz_queue_list.count(
    ) + gs_queue_list.count() + ga_queue_list.count()

    title = "东城街道行政办事" + start + "至" + end + "受理情况"
    bar = Bar(
        title,
        subtitle="总业务量为" + str(bumen_count_all),
        subtitle_color='#F00',
        subtitle_text_size=16,
        height=600,
        width=1920,
        title_pos="center",
    )
    bar.add(
        "业务量",
        bumen_name_list,
        bumen_count_list,
        is_label_show=True,
        legend_pos="left",
        xaxis_interval=0,  # 设置为0,强制显示所有标签
        xaxis_rotate=0,  # 倾斜角度:90~-90
    )
    print(bumen_name_list)
    print(bumen_count_list)
    print(time.time())
    return bar
Example #57
0
def test_bar_convert_xy_axis():
    bar = Bar("x 轴和 y 轴交换")
    bar.add("商家A", CLOTHES, clothes_v1)
    bar.add("商家B", CLOTHES, clothes_v2, is_convert=True)
    assert "average" not in bar._repr_html_()
Example #58
0
def test_bar():

    # bar_0
    attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    v1 = [5, 20, 36, 10, 75, 90]
    v2 = [10, 25, 8, 60, 20, 80]
    bar = Bar("柱状图数据堆叠示例")
    bar.add("商家A", attr, v1, is_stack=True)
    bar.add("商家B", attr, v2, is_stack=True)
    bar.render()

    # bar_1
    bar = Bar("标记线和标记点示例")
    bar.add("商家A", attr, v1, mark_point=["average"])
    bar.add("商家B", attr, v2, mark_line=["min", "max"])
    bar.render()

    # bar_2
    bar = Bar("x 轴和 y 轴交换")
    bar.add("商家A", attr, v1)
    bar.add("商家B", attr, v2, is_convert=True)
    bar.render()

    # bar_3
    attr = ["{}月".format(i) for i in range(1, 13)]
    v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
    v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
    bar = Bar("柱状图示例")
    bar.add("蒸发量", attr, v1, mark_line=["average"], mark_point=["max", "min"])
    bar.add("降水量", attr, v2, mark_line=["average"], mark_point=["max", "min"],
            is_datazoom_show=True, datazoom_range=[20, 60], datazoom_type='inside')
    bar.show_config()
    bar.render()

    # bar_3_1
    bar = Bar("柱状图示例")
    bar.add("蒸发量", attr, v1, mark_line=["average"], mark_point=["max", "min"])
    bar.add("降水量", attr, v2, mark_line=["average"], mark_point=["max", "min"],
            is_datazoom_show=True, datazoom_range=[50, 80])
    bar.show_config()
    bar.render()

    # bar_4
    import random

    attr = ["{}天".format(i) for i in range(30)]
    v1 = [random.randint(1, 30) for _ in range(30)]
    bar = Bar("Bar - datazoom - slider 示例")
    bar.add("", attr, v1, is_label_show=True, is_datazoom_show=True)
    bar.show_config()
    bar.render()

    # bar_5
    attr = ["{}天".format(i) for i in range(30)]
    v1 = [random.randint(1, 30) for _ in range(30)]
    bar = Bar("Bar - datazoom - inside 示例")
    bar.add("", attr, v1, is_datazoom_show=True, datazoom_type='inside', datazoom_range=[10, 25])
    bar.show_config()
    bar.render()

    # bar_6
    attr = ["{}天".format(i) for i in range(20)]
    v1 = [random.randint(1, 20) for _ in range(20)]
    bar = Bar("坐标轴标签旋转示例")
    bar.add("", attr, v1, xaxis_interval=0, xaxis_rotate=30, yaxis_rotate=30)
    bar.show_config()
    bar.render()
df.install_count = pd.to_numeric(df.install_count, downcast='integer', errors='ignore')

as_order_datas = df.sort_values('install_count', ascending=0).drop_duplicates(['app_name']).reset_index(drop=True)
most_ten = as_order_datas.head(10)

# print(most_ten.app_name.tolist())
'''下载量前10'''


def label_formatter(params):
    return params.value


page = Page()

bar = Bar("下载量最多的10个App")
bar.add('下载量',
        most_ten.app_name.tolist(),
        most_ten.install_count.tolist(),
        is_convert=True,
        xaxis_name="人次下载",
        )

page.add(bar)

'''cate_name 分类数目'''
df_type = df.cate_name.groupby(df['cate_name']).count()

line = Line('分类数目')
line.add(
    '数量',
Example #60
0
    month_counts,
    is_label_show=True,
    legend_pos='left',
    legend_orient="vertical",
    radius=[20, 60],
)

pie.render('月份统计饼图.html')

# 柱状统计

bar = Bar(
    "每月提交数量统计",
    "数据来源:guthub",

    # title_color="#fff",
    title_pos="center",
    width=1200,
    height=600,
)

bar.add(
    '',
    month,
    month_counts,
    is_label_show=True,
    is_visualmap=True,
)

bar.render('每月提交量统计—柱状图.html')