示例#1
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()
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)
    )
示例#3
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()
示例#4
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()
示例#5
0
def test_grid_line_pie():
    line = Line("折线图示例", width=1200)
    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 = [11, 12, 13, 10, 10, 10]
    pie = Pie("饼图示例", title_pos="55%")
    pie.add(
        "",
        CLOTHES,
        v1,
        radius=[45, 65],
        center=[65, 50],
        legend_pos="80%",
        legend_orient="vertical",
    )

    grid = Grid()
    grid.add(line, grid_right="55%")
    grid.add(pie, grid_left="60%")
    grid.render()
def draw_sentiment_pic(csv_file):
    attr, val = [], []
    info = count_sentiment(csv_file)
    info = sorted(info.items(), key=lambda x: x[0], reverse=False)  # dict的排序方法
    for each in info[:-1]:
        attr.append(each[0])
        val.append(each[1])
    line = Line(csv_file+":影评情感分析")
    line.add("", attr, val, is_smooth=True, is_more_utils=True)
    line.render(csv_file+"_情感分析曲线图.html")
示例#7
0
def test_line_es():
    v1 = [5, 20, 36, 10, 10, 100]
    line = Line("line-EffectScatter 示例")
    line.add("", CLOTHES, v1, is_random=True)
    es = EffectScatter()
    es.add("", CLOTHES, v1, effect_scale=8)

    overlap = Overlap()
    overlap.add(line)
    overlap.add(es)
    overlap.render()
示例#8
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()
示例#9
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()
示例#10
0
def test_line_user_define_marks():
    line = Line("折线图示例")
    line.add("商家A", CLOTHES, clothes_v1,
             mark_point=["average", "max", "min"],
             mark_point_symbol='diamond', mark_point_textcolor='#40ff27')
    line.add("商家B", CLOTHES, clothes_v2,
             mark_point=["average", "max", "min"],
             mark_point_symbol='arrow', mark_point_symbolsize=40)
    line.show_config()
    line.render()
示例#11
0
def test_grid_multiple_datazoom_index():
    line = Line("折线图示例", width=1200, height=700)
    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"], 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)

    grid = Grid()
    grid.add(line, grid_top="60%")
    grid.add(kline, grid_bottom="60%")
    grid.render()
示例#12
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()
示例#13
0
def iplot(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 axes is None:
        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]
    line = Line()
    
    style = gcf().get_style(axes, **kwargs)
    line.add(label, x_list, y_list, 
             yaxis_min=min(indicator),
             is_legend_show=legend_on,
             *args, **style)
    
    axes.add(line)
    
    gcf().add_axis(axes)
    return gcf()
示例#14
0
def test_line_negative_value():
    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"])
    line.render()
示例#15
0
def test_line_user_define_markpoint():
    line = Line("折线图示例")
    line.add("商家A", CLOTHES, clothes_v1,
             mark_point=["average", {
                 "coord": ["裤子", 10], "name": "这是我想要的第一个标记点"}])
    line.add("商家B", CLOTHES, clothes_v2, is_smooth=True,
             mark_point=[{
                 "coord": ["袜子", 80], "name": "这是我想要的第二个标记点"}])
    line.render()
示例#16
0
def test_line_log_yaxis():
    import math
    import random
    line = Line("折线图示例")
    line.add("商家A", CLOTHES,
             [math.log10(random.randint(1, 99999)) for _ in range(6)])
    line.add("商家B", CLOTHES,
             [math.log10(random.randint(1, 99999999)) for _ in range(6)],
             yaxis_type="log")
    line.render()
示例#17
0
def test_line_type_fil():
    line = Line("折线图-面积图示例")
    line.add("商家A", CLOTHES, clothes_v1, is_fill=True, line_opacity=0.2,
             area_opacity=0.4, symbol=None)
    line.add("商家B", CLOTHES, clothes_v2, is_fill=True, area_color='#000',
             area_opacity=0.3, is_smooth=True)
    assert '"step": true' not in line._repr_html_()
示例#18
0
def test_timeline_label_color():
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add(
        "bar",
        attr,
        [randint(10, 50) for _ in range(6)],
        label_color=["red", "#213", "black"],
    )
    line = Line()
    line.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_0 = Overlap()
    overlap_0.add(bar)
    overlap_0.add(line)

    bar_1 = Bar("2 月份数据", "数据纯属虚构")
    bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line_1 = Line()
    line_1.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap_1 = Overlap()
    overlap_1.add(bar_1)
    overlap_1.add(line_1)

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap_0, "1 月")
    timeline.add(overlap_1, "2 月")
    content = timeline._repr_html_()
    assert '"color": [' in content
    assert "red" in content
    assert "#213" in content
    assert "black" in content
示例#19
0
def test_grid_inverse_yaxis():
    attr = ["{}天".format(i) for i in range(1, 31)]
    line_top = Line("折线图示例", width=1200, 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",
    )
    grid = Grid()
    grid.add(line_top, grid_bottom="60%")
    grid.add(line_bottom, grid_top="50%")
    grid.render()
示例#20
0
def test_line_marks():
    line = Line("折线图示例")
    line.add("商家A", CLOTHES, clothes_v1, mark_point=["average"])
    line.add(
        "商家B",
        CLOTHES,
        clothes_v2,
        is_smooth=True,
        mark_line=["max", "average"],
    )
    line.render()
示例#21
0
def test_overlap_kline_line():
    import random

    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],
    ]
    attr = ["2017/7/{}".format(i + 1) for i in range(31)]
    kline = Kline("Kline-Line 示例")
    kline.add("日K", attr, v1)
    line_1 = Line()
    line_1.add("line-1", attr, [random.randint(2400, 2500) for _ in range(31)])
    line_2 = Line()
    line_2.add("line-2", attr, [random.randint(2400, 2500) for _ in range(31)])

    overlap = Overlap()
    overlap.add(kline)
    overlap.add(line_1)
    overlap.add(line_2)
    overlap.render()
示例#22
0
def draw_loss(generator, name):
    """
    画loss图
    :param generator: 传入的生成器
    :param name: 图表名
    :return:
    """
    line = Line(name)
    s = []
    last = 0
    for i in generator:
        s.append(get_loss(last=last, next=i[0]))
        last = i[0]
    line.add('', list(range(len(s))), s, is_smooth=True)
    line.render(name + '.html')
def draw_sentiment_pic(csv_file):
    attr, val = [], []
    info = count_sentiment(csv_file)
    info = sorted(info.items(), key=lambda x: x[0], reverse=False)  # dict的排序方法
    for each in info[:-1]:
        attr.append(each[0])
        val.append(each[1])

    print(info)
    print(attr)
    print(val)

    line = Line(csv_file + ":影评情感分析")
    line.add("test", attr, val, is_smooth=True, is_more_utils=True)
    line.render(csv_file + "_情感分析曲线图.html")
示例#24
0
 def grid(self):
     line = Line('折线图', width=1200)
     attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
     line.add('最高气温', attr, [11, 12, 14, 11, 12, 15, 16], mark_point=['max', 'min'], \
              mark_line=['average'])
     line.add('最低气温', attr, [1, -1, 2, 5, 2, 3, 0], mark_point=['max', 'min'], \
              mark_line=['average'], legend_pos='20%')
     attr = ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
     v1 = [11, 12, 14, 10, 11, 10]
     pie = Pie('饼图', title_pos='55%')
     pie.add('', attr, v1, radius=[45, 65], center=[65, 50], legend_pos='80%', \
             legend_orient='vertical')
     grid = Grid()
     grid.add(line, grid_right='55%')
     grid.add(pie, grid_left='60%')
示例#25
0
def get_png_v1(match_id, duration, path):
    gold = get_match_gold_xp_gap(match_id)[0]
    xp = get_match_gold_xp_gap(match_id)[1]

    print(len(gold))
    print(len(xp))

    attr = []
    for m in range(1, len(gold) + 1):
        attr.append(m)
    print(attr)
    line = Line("经济经验差异曲线")
    line.add("经济差异曲线", attr, gold, is_smooth=True, mark_line=["max", "min"])
    #line.show_config()
    line.render(path="{}".format(path))
示例#26
0
def DrawDistance(distances):
    line = Line('聚类距离走势图')
    attrs = []
    values = []
    i = 1
    for d in distances:
        attrs.append(i)
        values.append(d)
        i += 1
    line.add("距离",
             attrs,
             values,
             is_smooth=False,
             mark_point=["average", "max", 'min'])
    line.render('kmeansLine.html')
示例#27
0
    def draw_gpa_bar(self, terms):
        from pyecharts import Line
        from os import path

        avg_gpa = sum([t.gpa * t.total_credit
                       for t in terms]) / sum([t.total_credit for t in terms])
        line = Line("gpa折线图-平均{avg: .3f}".format(avg=avg_gpa))
        x = ["第{0}学期".format(t.term) for t in terms]
        y = [t.gpa for t in terms]
        y1 = [t.major_gpa for t in terms]
        line.add("全科GPA", x, y, is_stack=False, symbol='roundRect')
        line.add("主科GPA", x, y1, is_stack=False, symbol='triangle')
        save_path = path.join(__file__, "../GPA Line Figure.html")
        line.render(save_path)  # save it to file
        return save_path
示例#28
0
def plot_interactive_gross_leverage(positions: pd.DataFrame) -> Chart:
    """TODO: NotImplementedYet"""

    gl = timeseries.gross_lev(positions)
    line = Line("Gross Leverage")

    line.add("Gross Leverage", gl.index.strftime("%Y-%m-%d"),
             np.round(gl, 3).tolist(), is_datazoom_show=True,
             mark_line=["average"], datazoom_range=[0, 100],
             **PlottingConfig.LINE_KWARGS)

    line._option['color'][0] = PlottingConfig.GREEN
    line._option["series"][0]["markLine"]["lineStyle"] = {"width": 2}

    return line
示例#29
0
def test_grid_multiple_datazoom_index():
    line = Line("折线图示例", width=1200, 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)

    grid = Grid()
    grid.add(line, grid_top="60%")
    grid.add(kline, grid_bottom="60%")
    grid.render()
示例#30
0
def test_page():
    page = Page()
    line = Line("折线图示例")
    line.chart_id = "id_my_cell_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"],
    )

    # pie
    v1 = [11, 12, 13, 10, 10, 10]
    pie = Pie("饼图-圆环图示例", title_pos="center", width="600px")
    pie.add(
        "",
        CLOTHES,
        v1,
        radius=[40, 75],
        label_text_color=None,
        is_label_show=True,
        legend_orient="vertical",
        legend_pos="left",
    )

    page.add([line, pie, create_a_bar(TITLE)])
    # Start render and test
    html = page._repr_html_()
    # Test base html structure
    assert html.count("<script>") == html.count("</script>") == 2
    assert html.count("<div") == html.count("</div>") == 3
    assert html.count("require.config") == html.count("function(echarts)") == 1
    # Test some chart attributes
    json_encoded_title = json.dumps(TITLE)
    assert json_encoded_title in html
    assert "nbextensions/echarts" in html  # default jshost
    assert html.count("height:400px") == 3
    assert html.count("width:600px") == 1
    assert html.count("width:800px") == 2
    assert html.count("id_my_cell_line") == 6
示例#31
0
def plot_line_daily_close(title,
                          codes,
                          start,
                          end,
                          benchmark_code=get_benchmark_code(),
                          legend_top='15%',
                          datazoom_extra_type='both',
                          is_datazoom_extra_show=True,
                          datazoom_extra_orient='horizontal',
                          **kwargs):
    """使用 `pyechart` 绘制Line。使用 **收盘价格** 经过 **归一化** 后绘制。
    绘制图片时横坐标可以缩放。

    使用 `legend_top` 控制图例的位置。使其不会与标题重叠。

    Args:
        datazoom_extra_type: 参见 `line.add` 方法的同名参数
        is_datazoom_extra_show: 参见 `line.add` 方法的同名参数
        datazoom_extra_orient: 参见 `line.add` 方法的同名参数
        legend_top: 参见 `line.add` 方法的同名参数
        datazon
        title: 主标题
        codes: 待绘制的股票代码
        start: 开始日期
        end: 结束日期
        benchmark_code: 指数代码
        **kwargs: 参考 `Line` 中的参数

    Returns:(pyecharts.Line,pd.DataFrame)
    """
    line = Line(title, **kwargs)
    # 读取收盘价
    df = get_qfq_index_close(start, end)
    for code in codes:
        df = df.join(
            pd.DataFrame.from_dict(
                {code: get_qfq_stock_close(code, start, end)}))  # 取复权收盘价
    df = normalize_data(df.fillna(method='ffill'))  # 归一化,并且填充nan值
    line.add(benchmark_code, df.index.date, np.round(df[benchmark_code], 2))
    for code in codes:
        line.add(code,
                 df.index.date,
                 np.round(df[code], 2),
                 datazoom_extra_type=datazoom_extra_type,
                 legend_top=legend_top,
                 is_datazoom_extra_show=is_datazoom_extra_show,
                 datazoom_extra_orient=datazoom_extra_orient)
    return line, df
示例#32
0
def lines_member_by_pj(pj, data):
    """
    展示指定项目的分布
    :param pj: 指定的项目
    :param data: 数据集
    :return: 展示图
    """

    _t = []
    for _d in data:
        for _dd in data[_d]:
            if _dd not in _t:
                _t.append(_dd)

    _line = Line(u"",
                 width=100, height=60,
                 background_color='#b0bab9',
                 title_pos="center",
                 )

    _title = []
    for __t in sorted(_t):
        _title.append(__t)
    _title = _title[-12:]
    print _title

    _v = []
    for _i in range(len(_title)):
        _v.append(0)
    for _dd in sorted(data[pj]):
        if _dd not in _title:
            continue
        _idx = _title.index(_dd)
        _v[_idx] = data[pj][_dd]*10
    print _v

    _line.add(pj, _title, _v,
              is_fill=True,
              # is_stack=True,
              line_opacity=0.2,
              area_opacity=0.4,
              # is_smooth=True,
              is_legend_show=False,
              # is_label_show=False,
              is_focusnode=True,
              symbol=None)
    _line.options['toolbox']['show'] = False
    return _line.render_embed()
示例#33
0
 def view_growth_compare(self, score, **kwargs):
     """
     对比各条数据
     :param score: 刻度 [score]
     :param kwargs: {"name": [value],}
     """
     line = Line("销货曲线", width=1800, height=600, page_title="Sales line")
     for name, value in kwargs.items():
         line.add(name,
                  score,
                  value,
                  is_smooth=True,
                  mark_line=["max", "average"],
                  is_toolbox_show=False,
                  label_emphasis_textcolor="#000")
     line.render(path=self.BASE_PATH + "compare_line.html")
示例#34
0
def get_user_year():
    result = userDs.get_user_join_time()
    labels = []
    count = []
    total = 0
    for year in result:
        labels.append(year)
        user_count = result[year]
        count.append(user_count)
        total = user_count + total

    line = Line("新增用户年份分布")
    line.add("新增用户年份分布", labels, count, mark_line=["average"])
    fileName = 'user_join_data_new_user_year.html'
    line.render(fileName)
    return send_file(fileName)
示例#35
0
    def plotNet(self):

        stgL = self.__stglist
        netall = self.__net

        page = Page()
        line = Line(background_color="#FFF", width=1500, height=680)

        for Symbol in stgL.index:
            line.add(Symbol, list(netall.index), list(netall[Symbol].values), is_datazoom_show=True, datazoom_type="both",\
                 is_xaxislabel_align = True, tooltip_axispointer_type="cross", datazoom_xaxis_index=[0, 1],\
                 yaxis_min="dataMin"  ,yaxis_max="dataMax"  )

        kline = Line(background_color="#FFF", width=1500, height=680)
        kline.add('Total Net',
                  list(netall.index),
                  list(netall.netDay.values),
                  legend_top='bottom')
        grid = Grid(width=1500, height=680)
        grid.add(line, grid_bottom='50%')
        grid.add(kline, grid_top='50%')
        page.add(grid)
        page.render('./echart.html')
示例#36
0
def save_picture(name, data, p_path):
    if len(data) == 0 or p_path is None:
        return
    data_value = [x["value"] for x in data]
    line = Line(name, background_color='#EAEAEA')
    attr = list(range(0, len(data_value)))
    line.add("delta",
             attr,
             data_value,
             mark_point=["max", "min"],
             mark_line=["average"])
    render_file = "{}/{}.html".format(p_path, name)
    picture_file = "{}/{}.png".format(p_path, name)
    line.render(path=render_file, )
    make_a_snapshot(render_file, picture_file)
    print("save picture {}.png in {}".format(name, p_path))
示例#37
0
def bar_line(request):
    try:
        template = loader.get_template('echarts/line.html')

        line = Line('第一张图标', '副标题')
        line.add("服装", ["衣服", "鞋子", "袜子", "帽子", "眼镜"], [2, 4, 15, 6, 23], is_convert=True)
        context = dict(
                myechart=line.render_embed(),
                host=REMOTE_HOST,
                script_list=line.get_js_dependencies()
        )

    except Exception:
        raise Http404

    return render(request, 'echarts/line.html', context)
示例#38
0
def overlap(data):
    # line
    line = Line('star compare', width=1000, height=400)
    line.add("dashen star line", data['name'], data['star'], xaxis_rotate=45)
    movie_star = data['movie_star']/10
    line.add("movie star line", data['name'], movie_star, xaxis_rotate=45)
    # bar
    bar = Bar("star compare", width=1000, height=400)
    bar.add("dashen star bar", data['name'], data['star'], xaxis_rotate=45, is_label_show=True, is_datazoom_show=True)
    movie_star = data['movie_star'] / 10
    bar.add("movie star bar", data['name'], movie_star, xaxis_rotate=45, is_label_show=True, is_datazoom_show=True)
    # overlap
    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)
    overlap.render()
示例#39
0
def TrailingStop(path_name):
    with open(path_name, 'r', encoding="utf-8") as json_file:
        date_dict = json.loads(json_file.read())
# =============================================================================
#     从掘金回撤文件中获取浮动盈亏
# =============================================================================
    fpnl = []
    Pnl_old = []         #初试净收益列表
    for date in range(len(date_dict["indicatorDuration"])):
        if date != 0:
            fpnl.append(date_dict["indicatorDuration"][date]["fpnl"])
            Pnl_old.append(date_dict["indicatorDuration"][date]["nav"] - date_dict["cash"]['cumInout'] - date_dict["indicatorDuration"][date]["fpnl"])
    
    #新的对应每天持仓的收益列表
    Pnl_list = list(np.diff(Pnl_old))
    Pnl_list.append(0.0)
    
    #总收益
    net_profit = np.array(Pnl_list).sum()
    
    #该笔浮动亏损-该笔最终盈亏
    fpnl_pnl = []
    for index in range(len(fpnl)):
        if fpnl[index] < 0:
            fpnl_pnl.append((fpnl[index],Pnl_list[index]))
    fpnl_pnl.sort(reverse=True)
    fpnl_pnl = list(filter(lambda x: x[0]<-1, fpnl_pnl))
    
    Max_Drawdown = abs(np.array([item[0] for item in fpnl_pnl]).min())
    
    x3 = [(abs(item[0])/Max_Drawdown+0.6) for item in fpnl_pnl]
    y3 = []
    for i in range(len(x3)):
        sum_prodit = 0.0
        for ii in range(i,len(fpnl_pnl)):
            sum_prodit += fpnl_pnl[ii][0] - fpnl_pnl[ii][1]
        y3.append((net_profit+sum_prodit)/Max_Drawdown)

# =============================================================================
#     绘制TrailingStop
# =============================================================================
    from pyecharts import Line
        
    line = Line("TrailingStop")
    line.add("", x3, y3, mark_point=["average", "max", "min"]
        ,xaxis_name="Traill Stop Distance(%)",yaxis_name="Net Profit/Max DD")
    line.render("TrailingStop.html")
示例#40
0
    def show_analysis_chart(self,value):
        db = Database()
        db.open(clear_data=False)
        comment_count_list = db.get_comment_count_list_for_month(self.index + 1)
        from pyecharts import Bar, Line
        attr = []
        v = []

        for comment_count in comment_count_list:
            attr.append(comment_count['month'])
            v.append(comment_count['count'])

        bar = Bar('商品月评论数(bar)')

        bar.add(self.book_title, attr, v, is_stack=False, mark_point=['average'])

        bar.render('goods_comment_count_bar.html')

        line = Line('商品月评论数(line)')
        line.add(self.book_title, attr, v, mark_point=["max"])

        line.render("goods_comment_count_line.html")


        ui = Ui_AanlysisChart()
        dialog = QDialog()



        # 调用setupUi方法动态创建控件
        ui.setupUi(dialog)

        # 垂直布局按照从上到下的顺序进行添加按钮部件。
        vlayout = QVBoxLayout()
        dialog.setWindowTitle(self.book_title)

        dialog.setLayout(vlayout)
        dialog.browser = QWebEngineView()
        vlayout.addWidget(dialog.browser)
        # 加载本地页面
        url =  os.getcwd() + '/chart.html'
        dialog.browser.load(QUrl.fromLocalFile(url))

        # 显示窗口
        dialog.exec()

        db.close()
示例#41
0
def test_line_user_define_marks():
    line = Line("折线图示例")
    line.add(
        "商家A",
        CLOTHES,
        clothes_v1,
        mark_point=["average", "max", "min"],
        symbol_size=50,
        mark_point_symbol="diamond",
        mark_point_textcolor="#40ff27",
    )
    line.add(
        "商家B",
        CLOTHES,
        clothes_v2,
        mark_point=["average", "max", "min"],
        mark_point_symbol="arrow",
        mark_point_symbolsize=40,
    )
    assert '"symbolSize":50' not in line._repr_html_()
示例#42
0
def plot2MACD(Symbol):
    
    path = './data2/'+ Symbol + 'MACD.csv'
    df = pd.read_csv(path)
    
    l1 = Line('MACD of ' + Symbol, background_color="#FFF", width=1500, height=680)
    l1.add('DIFF',df['date'],df['DIFF'])
    l1.add('DEA',df['date'],df['DEA'])
    
    b1 = Bar(width=1500, height=680)
    b1.add('MACD',df['date'],df['MACD'])
    
    ov = Overlap()
    ov.add(l1)
    ov.add(b1)
    
    return ov
def drawLine(title, df, col):
    from pyecharts import Line
    if title == "NetValue":
        pic = "单位净值"
    if title == "Margin":
        pic = "保证金"
    line = Line(pic)
    dates = df.index
    for name in df.columns:
        line.add(name, dates, df.loc[:, name])
    #paramFilename='examples/WebTrader/app/templates/'+title +'.html'
    #path=os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
    #path=os.path.join(path,paramFilename)
    path = u'C:/vnpy-master190102/vnpy-master/examples/WebTrader/app/templates/' + title + '.html'
    if os.path.exists(path):
        os.remove(path)
    line.render(path)
示例#44
0
def create_look_city_line(data_df, city):
    """
        绘制出城市每个区的历史房价折线图
    """
    data_copy = data_df[(data_df['city'] != city)]
    data_index = data_copy.groupby('city').mean().round()
    data_index.reset_index(inplace=True)
    data_copy = data_copy.groupby(['year', 'city']).mean().round()
    data_copy.reset_index(inplace=True)
    line = Line(city + '各区历史房价', '2010-2019' + city + '各区历史房价折线图')
    for i in data_index['city']:
        line.add(i,
                 data_copy[data_copy['city'] == i]['year'],
                 data_copy[data_copy['city'] == i]['price'],
                 is_label_show=True,
                 legend_top='bottom')
    line.render(config.out_path + city + '.html')
def time_num_visualization(date):
    from pyecharts import Line
    date_list = list(date)
    set_date = sorted(list(set(date)))
    print(set_date)
    date_dict = {}
    date_num = []
    for i in range(len(set_date)):
        date_dict[str(set_date[i]).split()[0]] = date_list.count(set_date[i])
# 根据数量(字典的键值)排序
    date_name = []
    date_num = []
    #    print(sort_dict)
    for i in date_dict:
        date_name.append(i)
        date_num.append(date_dict[i])

    line = Line("我不是药神--电影评论数量日期折线图")
    line.add(
        "日期-评论数",
        date_name,
        date_num,
        is_fill=False,
        area_color="#fff",
        area_opacity=0.2,
        is_smooth=True,
        is_more_utils=True,
        is_label_show=False,
        is_xaxislabel_align=False,
        xaxis_max='2018-12-18',
        mark_point=[['max'], ['min']],
        mark_line=["average"],
        tooltip_trigger=
        "axis",  # 触发类型,item=数据项触发,默认,主要在散点图,饼图等无类目图中使用,xais=坐标轴触发,主要在柱状图,折线图等有类目的途中使用,none=什么都不触发
        tooltip_trigger_on=
        "mousemove",  # 触发条件, mousemove=鼠标移动的时候,click=电机的时候,mousemove|click=点击或移动的时候,none=不触发
        tooltip_axispointer_type=
        "shadow",  # 指示器类型,默认=line,直线,shadow=隐形,cross=十字准星
        tooltip_formatter='{c}',  # str类型,{a}=系列名称add第一个参数,{b}=对应的x轴值,{c}=x,y坐标
        tooltip_text_color="#000",  # 提示框文本的颜色
        tooltip_font_size=20,  # 提示框字体的大小
        tooltip_background_color="#fff",  # 提示框背景色
        tooltip_border_color="#fff",  # 提示框边框的颜色
        tooltip_border_width=1,  # 边框的宽度
    )
    line.render("c_num_line.html")
示例#46
0
 def getThanks(self):
     collection = self.spring['cityroute']
     count_thanks = collection.aggregate([
         {'$match':{'thanks_price':{'$gt':0}}},
         {'$group':{'_id':'$from_poi.city.city_name','avg_thanks_price':{'$avg':'$thanks_price'},'count_thanks':{'$sum':1}}}
     ])
     thanks_result = list(count_thanks)
     thanks_result = sorted(thanks_result,key=lambda city: city['avg_thanks_price'])
     print(thanks_result)
     thanksline = Line("哪里的乘客最壕气",page_title="哪里的乘客最壕气",**style.init_style)
     count_value = ['%.2f'%(thanks_result[3]['count_thanks']/11.74),'%.2f'%(thanks_result[4]['count_thanks']/46.34),'%.2f'%(thanks_result[6]['count_thanks']/17.32),'%.2f'%(thanks_result[7]['count_thanks']/27.15),'%.2f'%(thanks_result[8]['count_thanks']/20.83)]
     avg_value = ['%.2f'%(thanks_result[3]['avg_thanks_price']),'%.2f'%(thanks_result[4]['avg_thanks_price']),'%.2f'%(thanks_result[6]['avg_thanks_price']),'%.2f'%(thanks_result[7]['avg_thanks_price']),'%.2f'%(thanks_result[8]['avg_thanks_price'])]
     attr = [thanks_result[3]['_id'], thanks_result[4]['_id'], thanks_result[6]['_id'], thanks_result[7]['_id'],
             thanks_result[8]['_id']]
     thanksline.add("比例",attr,count_value,**line_style)
     thanksline.add("平均加价",attr,avg_value,**line_style)
     thanksline.render("results/thanksline.html")
示例#47
0
def plot_in_out_of_all_main_river(title="全流域信息来水出水.html", day_delta=30):
    """
    将河流的入水量,出水量信息按时间统计求和。
    :param day_delta:
    :return:
    """
    engine1 = init_engine(db="power_supply", )
    datetime_now = datetime.datetime.now()
    last_month = (
        datetime_now -
        datetime.timedelta(days=day_delta)).strftime("%Y-%m-%d 00:00:00")
    df1 = pd.read_sql(
        "SELECT * FROM sc_main_river_inflow WHERE official_update_time> '{last_month}'"
        .format(last_month=last_month), engine1)
    df2 = pd.read_sql(
        "SELECT * FROM sc_main_river_outflow WHERE official_update_time> '{last_month}'"
        .format(last_month=last_month), engine1)
    print(df2["river_system"].unique())

    line2 = Line("全流域水流量", width="1600px", height="800px")
    df1_1 = df1.groupby(axis=0, by=["official_update_time"
                                    ]).aggregate({"water_inflow": "sum"})
    df1_2 = df1_1.reset_index()
    df2_1 = df2.groupby(axis=0, by=["official_update_time"
                                    ]).aggregate({"water_outflow": "sum"})
    df2_2 = df2_1.reset_index()
    line2.add(
        "全流域河流水量图-来",
        df1_2["official_update_time"].map(lambda x: x.strftime("%Y-%m-%d")),
        df1_2["water_inflow"])
    line2.add(
        "全流域河流水量图-出",
        df2_2["official_update_time"].map(lambda x: x.strftime("%Y-%m-%d")),
        df2_2["water_outflow"])

    line2.render(title)
示例#48
0
def mutual_info(param):
    params = common.parse_param(param)
    path_a = params[0]
    ids = []
    mis = []
    i = 0
    for path in params:
        res = _mutual_info(path, path_a)
        print res
        if i != 0:
            ids.append(i)
            mis.append(res["mi_r"] / 0.6)
        i = i + 1
    bar = Line("我的第一个图表", "这里是副标题")
    bar.add("mi", ids, mis, is_more_utils=True)
    bar.render()
    return
示例#49
0
def test_grid_line_pie():
    line = Line("折线图示例", width=1200)
    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=[65, 50], legend_pos="80%",
            legend_orient='vertical')

    grid = Grid()
    grid.add(line, grid_right="55%")
    grid.add(pie, grid_left="60%")
    grid.render()
示例#50
0
def crawl_mail(workQueue):
    date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    attrs.append(date)
    url = 'https://www.huobi.pro/zh-cn/eos_usdt/exchange/'
    html = get_html(url)
    # 创建request对象
    soup = BeautifulSoup(html, 'lxml')
    # 找出div中的内容
    soup_text = soup.find('div', class_='coin_list')
    btc, eth, eos, xrp = process_result(soup_text.text.strip())
    send_text = btc + " |" + eth + " |" + eos + " |" + xrp
    print send_text
    workQueue.put(btc)
    workQueue.put(eth)
    workQueue.put(eos)
    workQueue.put(xrp)
    while workQueue.qsize() > 0:
        print workQueue.qsize()
        coin = workQueue.get()
        results = coin.split(" ")
        name = results[0]
        price = results[1]
        increase = results[2]
        if cmp(name, "btc") == 0:
            btcs.append(price)
        elif cmp(name, "eos") == 0:
            eoss.append(price)
        elif cmp(name, "eth") == 0:
            eths.append(price)
        elif cmp(name, "xrp") == 0:
            xrps.append(price)
        alertMail(increase, price, send_text)
    line = Line("huobi 主区大盘btc")
    line.add("btc", attrs, btcs, is_smooth=True, mark_line=["max", "average"])
    line.show_config()
    line.render()
示例#51
0
def draw_sentiment_pic(comments):
    print("正在处理观众情感曲线......")
    score = comments['score'].dropna()  # 获取观众评分
    data = Counter(score).most_common()  # 记录相应评分对应的的评论数
    data = sorted(data, key=lambda data: data[0])  # 使用lambda表达式对数据按评分进行排序
    line = Line('《流浪地球》观众情感曲线', '数据来源:猫眼电影 数据分析:16124278-王浩',
                **style_others.init_style)  # 初始化
    attr, value = line.cast(data)  # 传值

    for i, v in enumerate(attr):  # 将分数修改为整数便于渲染图上的展示
        attr[i] = v * 2

    line.add("",
             attr,
             value,
             is_smooth=True,
             is_more_utils=True,
             yaxis_max=380000,
             xaxis_max=10)  # 加入数据和其它参数
    line.render("./output/观众情感分析-曲线图.html")  # 渲染
    print("观众情感曲线已完成!!!")
示例#52
0
def test_line_type_fil():
    line = Line("折线图-面积图示例")
    line.add(
        "商家A",
        CLOTHES,
        clothes_v1,
        is_fill=True,
        line_opacity=0.2,
        area_opacity=0.4,
        symbol=None,
    )
    line.add(
        "商家B",
        CLOTHES,
        clothes_v2,
        is_fill=True,
        area_color="#000",
        area_opacity=0.3,
        is_smooth=True,
    )
    assert '"step": true' not in line._repr_html_()
示例#53
0
def test_line_user_define_markpoint():
    line = Line("折线图示例")
    line.add(
        "商家A",
        CLOTHES,
        clothes_v1,
        mark_point=["average", {"coord": ["裤子", 10], "name": "这是我想要的第一个标记点"}],
    )
    line.add(
        "商家B",
        CLOTHES,
        clothes_v2,
        is_smooth=True,
        mark_point=[{"coord": ["袜子", 80], "name": "这是我想要的第二个标记点"}],
    )
    html_content = line._repr_html_()
    assert '"value": 80' in html_content
    assert '"value": 10' in html_content
示例#54
0
def test_line_user_define_marks():
    line = Line("折线图示例")
    line.add(
        "商家A",
        CLOTHES,
        clothes_v1,
        mark_point=["average", "max", "min"],
        symbol_size=50,
        mark_point_symbol="diamond",
        mark_point_textcolor="#40ff27",
    )
    line.add(
        "商家B",
        CLOTHES,
        clothes_v2,
        mark_point=["average", "max", "min"],
        mark_point_symbol="arrow",
        mark_point_symbolsize=40,
    )
    assert '"symbolSize":50' not in line._repr_html_()
示例#55
0
def test_line_type_stack():
    line = Line("折线图-数据堆叠示例")
    line.add("商家A", CLOTHES, clothes_v1, is_stack=True, is_label_show=True)
    line.add("商家B", CLOTHES, clothes_v2, is_stack=True, is_label_show=True)
    line.render()
示例#56
0
def test_line_type_step():
    line = Line("折线图-阶梯图示例")
    line.add("商家A", CLOTHES, clothes_v1, is_step=True, is_label_show=True)
    assert '"step": true' in line._repr_html_()
示例#57
0
def graphpage(labels,mode_combo,startdate,enddate,optInterval,width1, height1):
    #optInterval='D/W/M' labels

    startdate = startdate.replace("/","-")#convert to tushare readable date
    enddate = enddate.replace("/","-")

    page = Page()

    for label in labels:  # generate numbers of graphs according to numbers of queries in treewidget
        label1 = re.split("-", label)
        overlap = Overlap()

        if label1[2]!="分笔" and label1[2]!="季度饼图": #"K线" "复权" "历史分钟"
            if mode_combo == "复权":
            #if optInterval == "qfq" or optInterval == "hfq":#复权
                array = ts.get_h_data(label1[1], start=startdate, end=enddate, autype="qfq")
                array = array.sort_index()
                time = array.index.format()  # 日期正是index
            elif mode_combo == "K线":
            #elif optInterval.isalnum() :#历史K线
                array = ts.get_k_data(label1[1], start=startdate, end=enddate, ktype=optInterval)
                time = array['date'].tolist()  # array.date
            elif mode_combo == "历史分钟":
                array_bfr = ts.get_tick_data(label1[1], date=startdate)
                array_bfr.sort_values("time")
                a = startdate + " " + array_bfr["time"]
                array_bfr["time"] = a
                array_bfr["time"] = pd.to_datetime(a)
                array_bfr = array_bfr.set_index("time")
                if label1[2] != "Volume" and label1[2] != "Amount":
                    price_df = array_bfr["price"].resample(optInterval).ohlc()  # resample重新取样,选出ohlc=open/high/low,提取除价格之外另外4列.close,tushare是ohcl
                    price_df = price_df.dropna()
                    array = price_df
                    time = price_df.index.format()

                elif label1[2] == "Volume":
                    vols = array_bfr["volume"].resample(optInterval).sum()  #resample重新取样,累加间隔内数值 relevant data processing algorithm taken from Jimmy, Creator of Tushare
                    vols = vols.dropna()
                    vol_df = pd.DataFrame(vols, columns=["volume"])
                    array = vol_df
                    time = vol_df.index.format()
                else:
                    amounts = array_bfr["amount"].resample(optInterval).sum()
                    amounts = amounts.dropna()
                    amount_df = pd.DataFrame(amounts, columns=["amount"])
                    array = amount_df
                    time = amount_df.index.format()

            #绘图方法

            if label1[2] == 'Kline':
                re_array = array[['open', 'close', 'high', 'low']]
                data_li = list(row.tolist() for index, row in re_array.iterrows())  # data_list = list(re_array.as_matrix())
                close = array['close'].tolist()
                kline = Kline(label1[0] + "-" + optInterval, width=width1*10/11, height = (height1*10/11) / len(labels))
                kline.add(label1[0], time, data_li, is_datazoom_show=True, datazoom_type="slider", yaxis_interval=1)
                overlap.add(kline)

                if len(close) > 10:
                    ma10 = calculateMa(close, 10)
                    line1 = Line(title_color="#C0C0C0")
                    line1.add(label1[0] + "-" + "MA10", time, ma10)
                    overlap.add(line1)
                if len(close) > 20:
                    ma20 = calculateMa(close, 20)
                    line2 = Line(title_color="#C0C0C0")
                    line2.add(label1[0] + "-" + "MA20", time, ma20)
                    overlap.add(line2)
                if len(close) > 30:
                    ma30 = calculateMa(close, 30)
                    line3 = Line(title_color="#C0C0C0")
                    line3.add(label1[0] + "-" + "MA30", time, ma30)
                    overlap.add(line3)

                page.add(overlap)
            else:#When label1[2]==open/close/volume
                if label1[2] == 'Open':
                    list_aft = array['open'].tolist()
                elif label1[2] == 'Close':
                    list_aft = close
                elif label1[2] == 'High':
                    list_aft = array['high'].tolist()
                elif label1[2] == 'Low':
                    list_aft = array['low'].tolist()
                elif label1[2] == 'Volume':#volume
                    list_aft = array['volume'].tolist()
                else:#amount
                    list_aft = array['amount'].tolist()

                line = Line(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
                line.add(label1[0] + "-" + label1[2], time, list_aft, is_datazoom_show=True, yaxis_max="dataMax",
                         yaxis_min="dataMin", datazoom_type="slider")
                overlap.add(line)
                page.add(overlap)


        elif label1[2]=="分笔":
            array = ts.get_tick_data(label1[1], date=startdate)
            array = array.sort_values("time")
            date = array["time"].tolist()
            amount = array["amount"].tolist()
            atype = array["type"].tolist()
            price = array["price"].tolist()
            flag = ["bar" for i in date]
            for idx, val in enumerate(atype):
                if val == "卖盘":
                    amount[idx] = -amount[idx]
                if val == "中性盘":
                    amount[idx] = 0

            returnarray = list(zip(date, amount, flag, price))

            form = [e[1] for e in returnarray]
            time = [d[0] for d in returnarray]

            bar = Bar(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
            bar.add(label1[0] + "-" + label1[2], time, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax")
            overlap.add(bar)

            line = Line(label1[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels))
            price = [e[3] for e in returnarray]
            line.add(label1[0] + "price", time, price, yaxis_min="dataMin", yaxis_max="dataMax", is_datazoom_show=True,
                     datazoom_type="slider",
                     yaxis_type="value")
            overlap.add(line, yaxis_index=1, is_add_yaxis=True)
            page.add(overlap)
        elif label1[2]=="季度饼图":
            datestr = startdate.split("-")
            thisyear = datestr[0]
            df2 = ts.top10_holders(code=label1[1], gdtype="1")
            test = df2[1]["quarter"].tolist()
            df_ready = df2[1]
            idxlist = []
            for idx, val in enumerate(test):
                a = val.split("-")
                if a[0] == thisyear:
                    # print a[0],idx
                    idxlist.append(idx)
            thing = df_ready.loc[idxlist]
            thing = thing.sort_values(["quarter", "name"])
            # print a[0],id
            name = thing["name"].tolist()
            value = thing["hold"].tolist()
            quarter = thing["quarter"].tolist()
            namearray = [name[i:i + 10] for i in range(0, len(name), 10)]
            valuearray = [value[j:j + 10] for j in range(0, len(value), 10)]
            quarterarray = [quarter[k:k + 10] for k in range(0, len(quarter), 10)]

            flag = ["pie" for i in namearray]
            num = [len(value) for k in namearray]
            returnarray = list(zip(namearray, valuearray, quarterarray, flag, num))

            timeline = Timeline(is_auto_play=False, timeline_bottom=0)  # zip(namearray,valuearray,quarter,flag,num)
            namearray = [c[0] for c in returnarray]
            valuearray = [d[1] for d in returnarray]
            quarter = [e[2] for e in returnarray]
            num = returnarray[0][4]

            for x in range(0, int(num / 10)):
                list1 = valuearray[x]
                names = namearray[x]
                quarters = quarter[x][0]

                for idx, val in enumerate(list1):
                    list1[idx] = float(val)

                pie = Pie(label1[0] + "-" + "前十股东", width=width1 * 10 / 11, height=(height1 * 10 / 11))

                pie.add(label1[0] + "-" + "前十股东", names, list1, radius=[30, 55], is_legend_show=False,
                        is_label_show=True, label_formatter="{b}: {c}\n{d}%")
                timeline.add(pie, quarters)
                # namearray = [y for y in namearray[x]]
            timeline.render()

    page.render()
示例#58
0
import json
import sys
import glob
import os
from pyecharts import Line

def load_js(jsfile):
    x_axis = []
    points = []
    with open(jsfile, 'r') as fp:
        while True:
            l = fp.readline()
            if not l:
                break
            deal_dict = json.loads(l)
            x_axis.append(deal_dict['dealDate'][0])
            points.append(deal_dict['unitPrice'][0])
    return x_axis, points

if __name__ == '__main__':
    dir_path = sys.argv[1]
    curve_name = ''
    line = Line("Deal Curve")
    cwd = os.getcwd()
    os.chdir(dir_path)
    for js in glob.glob("*.json"):
        x_axis, points = load_js(js)
        curve_name = js[:js.find(".json")]
        line.add(curve_name, x_axis, points, is_stack=True, is_label_show=True)
    os.chdir(cwd)
    line.render()
示例#59
0
def test_page_grid_timeline_overlap():
    # Grid
    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%")

    # Timeline
    bar_1 = Bar("2012 年销量", "数据纯属虚构")
    bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_2 = Bar("2013 年销量", "数据纯属虚构")
    bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_3 = Bar("2014 年销量", "数据纯属虚构")
    bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_4 = Bar("2015 年销量", "数据纯属虚构")
    bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)])

    bar_5 = Bar("2016 年销量", "数据纯属虚构", height=720, width=1200)
    bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)])
    bar_5.add(
        "冬季",
        CLOTHES,
        [randint(10, 100) for _ in range(6)],
        is_legend_show=True,
    )

    timeline = Timeline(is_auto_play=True, timeline_bottom=0)
    timeline.add(bar_1, "2012 年")
    timeline.add(bar_2, "2013 年")
    timeline.add(bar_3, "2014 年")
    timeline.add(bar_4, "2015 年")
    timeline.add(bar_5, "2016 年")

    # Overlap
    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(height=720, width=1200)
    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)

    page = Page()
    page.add(grid)
    page.add(timeline)
    page.add(overlap)
    page.render()
示例#60
0
def test_more():
    page = Page()

    # line
    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"],
    )

    # pie
    v1 = [11, 12, 13, 10, 10, 10]
    pie = Pie("饼图-圆环图示例", title_pos="center")
    pie.add(
        "",
        CLOTHES,
        v1,
        radius=[40, 75],
        label_text_color=None,
        is_label_show=True,
        legend_orient="vertical",
        legend_pos="left",
    )

    page.add([line, pie])

    # kline
    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 线图示例")
    kline.add(
        "日K",
        ["2017/7/{}".format(i + 1) for i in range(31)],
        v1,
        is_datazoom_show=True,
    )
    page.add(kline)

    # radar
    schema = [
        ("销售", 6500),
        ("管理", 16000),
        ("信息技术", 30000),
        ("客服", 38000),
        ("研发", 52000),
        ("市场", 25000),
    ]
    v1 = [[4300, 10000, 28000, 35000, 50000, 19000]]
    v2 = [[5000, 14000, 28000, 31000, 42000, 21000]]
    radar = Radar("雷达图示例")
    radar.config(schema)
    radar.add("预算分配", v1, is_splitline=True, is_axisline_show=True)
    radar.add(
        "实际开销",
        v2,
        label_color=["#4e79a7"],
        is_area_show=False,
        legend_selectedmode="single",
    )
    page.add(radar)

    # 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)

    # wordcloud
    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",
    ]
    value = [
        10000,
        6181,
        4386,
        4055,
        2467,
        2244,
        1898,
        1484,
        1112,
        965,
        847,
        582,
        555,
        550,
        462,
        366,
        360,
        282,
        273,
        265,
    ]
    wordcloud = WordCloud(width=1300, height=620)
    wordcloud.add("", name, value, word_size_range=[30, 100], rotate_step=66)
    page.add(wordcloud)

    # liquid
    liquid = Liquid("水球图示例")
    liquid.add("Liquid", [0.6])
    page.add(liquid)
    assert len(page) == 7
    assert isinstance(page[0], Line)
    assert (
        ("echarts" in page.js_dependencies)
        or ("echarts.min" in page.js_dependencies)
    )
    page.render()