예제 #1
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
예제 #2
0
def avg():
    df = pd.read_csv('maoyan2.csv', error_bad_lines=False)
    df.round(2)
    # 根据日期统计各天的平均值,并保留两位小数
    date_score_avg = df.groupby('date')['score'].mean().round(2)*2
    # 根据评分数据生成柱状图

    bar = Bar('评分走势图', '数据来源:不正经程序员-采集自猫眼',
              title_pos='center', width=1500, height=600)
    # line = Line()
    # line.add('', attr, value)
    bar.add('', date_score_avg.index, date_score_avg.values, is_visualmap=False, visual_range=[0, 3500], visual_text_color='#fff', is_more_utils=True,
            is_label_show=True, xaxis_interval=0, xaxis_rotate=30, mark_line=["average"])
    overlap = Overlap()
    overlap.add(bar)
    # overlap.add(line)
    overlap.show_config()
    overlap.render(
        'picture\评分走势图.html')
        
    # 根据日期统计各天的平均值,并保留两位小数
    date_positive_prob_avg = df.groupby('date')['positive_prob'].mean().round(2)
    bar = Bar('评论情感指数走势图', '数据来源:不正经程序员-采集自猫眼',
              title_pos='center', width=1500, height=600)
    # line = Line()
    # line.add('', attr, value)
    bar.add('', date_positive_prob_avg.index, date_positive_prob_avg.values, is_visualmap=False, visual_range=[0, 3500], visual_text_color='#fff', is_more_utils=True,
            is_label_show=True, xaxis_interval=0, xaxis_rotate=30, mark_line=["average"])
    overlap = Overlap()
    overlap.add(bar)
    # overlap.add(line)
    overlap.show_config()
    overlap.render(
        'picture\评论情感指数走势图.html')
예제 #3
0
def test_timeline_bar_line():

    from pyecharts import Overlap
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("Line - Bar 示例")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line = Line()
    line.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)

    bar_1 = Bar("Line")
    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)
    overlap_1.get_chart()

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap.get_chart(), '2012')
    timeline.add(overlap_1.get_chart(), '2013')
    timeline.render()
예제 #4
0
def test_timeline_bar_line():

    from pyecharts import Overlap
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    line = Line()
    line.add("line", attr, [randint(50, 80) for _ in range(6)])
    overlap = Overlap()
    overlap.add(bar)
    overlap.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)

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

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

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

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap.chart, '1 月')
    timeline.add(overlap_1.chart, '2 月')
    timeline.add(overlap_2.chart, '3 月')
    timeline.add(overlap_3.chart, '4 月')
    timeline.add(overlap_4.chart, '5 月')
    timeline.render()
예제 #5
0
def test_timeline_bar_line():
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    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)

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

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

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

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap_0, '1 月')
    timeline.add(overlap_1, '2 月')
    timeline.add(overlap_2, '3 月')
    timeline.add(overlap_3, '4 月')
    timeline.add(overlap_4, '5 月')
    assert len(timeline._option.get("baseOption").get("series")) == 10
    timeline.render()
예제 #6
0
def test_timeline_bar_line():
    attr = ["{}月".format(i) for i in range(1, 7)]
    bar = Bar("1 月份数据", "数据纯属虚构")
    bar.add("bar", attr, [randint(10, 50) for _ in range(6)])
    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)

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

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

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

    timeline = Timeline(timeline_bottom=0)
    timeline.add(overlap_0, "1 月")
    timeline.add(overlap_1, "2 月")
    timeline.add(overlap_2, "3 月")
    timeline.add(overlap_3, "4 月")
    timeline.add(overlap_4, "5 月")
    timeline.render()
예제 #7
0
	def missing_check(df,columns,miss_rate=0.8,handling=None):
		temp = pd.DataFrame(df[columns].isnull().sum())
		temp = temp.reset_index().rename(columns={'index':'feature',0:'missing'})
		temp = temp.sort_values('missing',ascending=True)
		temp['missing_rate'] = np.round(temp['missing']/df.shape[0],2)*100
		temp = temp[temp['missing_rate']>miss_rate]
		attr = temp.feature.values.tolist()
		v1 = temp.missing.values.tolist()
		v2 = temp.missing_rate.values.tolist()
		bar = Bar()
		bar.add('缺失量',attr,v1,is_stack=True,is_datazoom_show=True,datazoom_type='both',datazoom_range=[0,100],
				label_color=['#0081FF','#FF007C'],is_visualmap=True, visual_type='size',visual_range=[0,100],
				visual_range_size=[10,10],is_yaxislabel_align=False,visual_dimension=1,tooltip_text_color='#000000',
				label_emphasis_textcolor='#000000',is_more_utils=True,yaxis_rotate=45,label_emphasis_pos='right',
				is_convert=True)
		line=Line()
		line.add('缺失率', attr, v2, yaxis_formatter="%", yaxis_min=0,yaxis_max=100,label_emphasis_textcolor='#000000',line_width=3,
				label_emphasis_pos='right',is_convert=True)
		overlap = Overlap(width=1000,height =np.round(temp.shape[0]/2)*30)
		overlap.add(bar)
		overlap.add(line, xaxis_index=1, is_add_xaxis=True)
		if handling == None:
			return overlap
		elif handling == 'drop':
			return temp['feature'].values.tolist()
예제 #8
0
 def drawfunc(self,
              A,
              text,
              yaxis_max=200000,
              yaxis_force_interval=0.25,
              width=1000):
     '''坏账率绘图函数'''
     bar = Bar(text, title_pos='center', width='100%')
     line = Line(text, title_pos='center', width='100%')
     bar.add("好客户",
             A.iloc[:, 0].tolist(),
             A['好客户'].tolist(),
             yaxis_min=0,
             yaxis_max=yaxis_max,
             is_label_show=True,
             label_pos='inside',
             label_color=['#FFB6B9'],
             legend_pos='right',
             legend_orient='vertical',
             is_stack=True)
     bar.add("坏客户",
             A.iloc[:, 0].tolist(),
             A['坏账'].tolist(),
             yaxis_min=0,
             yaxis_max=yaxis_max,
             is_label_show=True,
             label_pos='inside',
             label_color=['#BBDED6'],
             legend_pos='right',
             legend_orient='vertical',
             is_stack=True)
     line.add('坏账率',
              A.iloc[:, 0].tolist(),
              A['坏账率'].tolist(),
              yaxis_min=0,
              yaxis_max=1,
              yaxis_force_interval=yaxis_force_interval,
              is_smooth=True,
              legend_pos='right',
              point_symbol='circle',
              legend_orient='vertical',
              line_width=2,
              is_label_show=True)
     line.add('总体坏账率',
              A.iloc[:, 0].tolist(),
              A['总体坏账率'].tolist(),
              yaxis_min=0,
              yaxis_max=1,
              yaxis_force_interval=yaxis_force_interval,
              is_smooth=True,
              legend_pos='right',
              legend_orient='vertical',
              line_width=2,
              line_type='dotted')
     overlap = Overlap(width='100%')
     overlap.add(bar)
     overlap.add(line, is_add_yaxis=True, yaxis_index=1)
     grid = Grid(width=width)
     grid.add(overlap, grid_right='10%')
     return grid
def moneyflow_lgt(date_start, date_end, df, save_path_moneyflow_lgt):

    df = df.assign(hgt=df.hgt.apply(lambda x: round(x / 100, 2)))
    df = df.assign(sgt=df.sgt.apply(lambda x: round(x / 100, 2)))
    df = df.assign(
        north_money=df.north_money.apply(lambda x: round(x / 100, 2)))

    title = ' 资金流向 - 陆股通(亿元)'
    subtitle = '    GZH: 摸鱼大佬'
    bar = Bar(title,
              subtitle,
              title_pos=0.1,
              subtitle_text_size=15,
              subtitle_color='#aa8')
    # bar.use_theme("macarons")
    bar.add("沪股通", df['trade_date'], df['hgt'], bar_category_gap='40%')
    bar.add("深股通", df['trade_date'], df['sgt'], bar_category_gap='40%')
    line = Line()
    line.add("北上资金",
             df['trade_date'],
             df['north_money'],
             mark_line=['average'],
             mark_point=['min', 'max'])
    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line, is_add_xaxis=False)  #是否新增一个 x 坐标轴,默认为 False
    render_path = save_path + 'moneyflow_lgt_' + date_end + '.png'
    # bar.render(path=render_path)
    overlap.render(path=render_path)
    # pic_zoom(render_path, save_path_tgbhotstock, 740)
    print('moneyflow_lgt done: ' + render_path)
    return render_path
예제 #10
0
파일: echart.py 프로젝트: onecans/my
def show_overview_day2(category, method, name):
    # if not _check_category(category):
    #     return

    se = SE()
    m = getattr(se, method)
    _df1 = m()
    df1 = _df1[[
        category,
    ]]
    _, df2 = get_line(indexs.get(category, '000001'), index=True)
    df1, df2 = reindex([df1, df2])

    line1 = Line()
    if method in ('get_market_val', 'get_negotiable_val') \
            and category in ('SZ', 'CYB', 'ZXQY'):
        line1.add(name,
                  df1.index,
                  df1[category] / 100000000,
                  is_datazoom_show=False)
    else:
        line1.add(name, df1.index, df1[category], is_datazoom_show=False)
    line2 = Line()
    line2.add('index: %s' % indexs.get(category, '000001'),
              df2.index,
              df2.high,
              is_datazoom_show=True)

    overlap = Overlap()
    overlap.add(line1)
    # 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1
    # 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变
    overlap.add(line2, yaxis_index=1, is_add_yaxis=True)
    return overlap
예제 #11
0
def xuqiu_diqu_mon(conn, width, height, mon):
    sql_xuqiu_diqu = "select name,count,mj from kanban_xuqiu_diqu where year(date_sub(create_date,interval 1 month))='%s'" \
                     "and month(date_sub(create_date,interval 1 month))='%s' order by mj desc"%(str(mon)[:4],str(mon)[-2:])
    data_xuqiu_diqu = pd.read_sql(sql_xuqiu_diqu, conn)

    xuqiu_diqu_name = list(data_xuqiu_diqu.iloc[:, 0])
    xuqiu_diqu_mj = list(data_xuqiu_diqu.iloc[:, 2])
    xuqiu_diqu_count = list(data_xuqiu_diqu.iloc[:, 1])

    xuqiu_diqu_title = str(mon)[:4] + '年' + str(mon)[-2:] + '月土流网土地需求区域分布'
    xuqiu_diqu_bar = Bar(xuqiu_diqu_title)
    xuqiu_diqu_bar.add("面积(亩)",
                       xuqiu_diqu_name,
                       xuqiu_diqu_mj,
                       xaxis_interval=0,
                       xaxis_rotate=90)
    xuqiu_diqu_line = Line()
    xuqiu_diqu_line.add("宗数",
                        xuqiu_diqu_name,
                        xuqiu_diqu_count,
                        xaxis_interval=0,
                        xaxis_rotate=90)

    xuqiu_diqu_overlap = Overlap(height=height, width=width)
    xuqiu_diqu_overlap.add(xuqiu_diqu_bar)
    xuqiu_diqu_overlap.add(xuqiu_diqu_line, yaxis_index=1, is_add_yaxis=True)
    xuqiu_diqu_overlap.render()

    return xuqiu_diqu_overlap
예제 #12
0
def gen_zwyx_type(zwlb):
    qs = ZpZwyxByTypeModel.objects
    if zwlb:
        qs = qs.filter(zwlb=zwlb)
        path = f'zwyx_type/{zwlb}.html'
    else:
        path = 'zwyx_type.html'
    # 当月职位月薪与公司性质
    df = read_frame(qs.all())
    if len(df) > 0:
        page = Page()
        Grid_chart1 = Timeline(width=1500, height=450, timeline_bottom=0)
        Grid_chart2 = Timeline(width=1500, height=450, timeline_bottom=0)
        df_group = df.groupby(['year', 'month'])
        for name, group in df_group:
            month = group['month'].tolist()[0]
            year = group['year'].tolist()[0]
            df_new = group.groupby('type').apply(get_echarts_all_by_zwyx_value,
                                                 'type')
            # 薪资
            Overlap_chart = Overlap(width=800, height=450)
            bar_chart = Bar(f'{zwlb}职位月薪与公司性质')
            bar_chart.add('最低薪资',
                          df_new['type'].tolist(),
                          df_new['min_zwyx'].tolist(),
                          is_label_show=True,
                          is_more_utils=True)
            bar_chart.add('最高薪资',
                          df_new['type'].tolist(),
                          df_new['max_zwyx'].tolist(),
                          is_label_show=True,
                          is_more_utils=True)
            line_chart = Line()
            line_chart.add("平均薪资",
                           df_new['type'].tolist(),
                           [(a + b) / 2
                            for a, b in zip(df_new['min_zwyx'].tolist(),
                                            df_new['max_zwyx'].tolist())],
                           is_label_show=True)
            Overlap_chart.add(bar_chart)
            Overlap_chart.add(line_chart)
            Grid_chart1.add(Overlap_chart, f'{year}年{month}月')
            # 职位量
            chart3 = Pie(f'{zwlb}职位量及招聘人数', width=1500)
            chart3.add('职位量'.format(zwlb),
                       df_new['type'].tolist(),
                       df_new['count'].tolist(),
                       is_label_show=True,
                       is_stack=True,
                       center=[25, 50])
            chart3.add('招聘人数'.format(zwlb),
                       df_new['type'].tolist(),
                       df_new['zprs'].tolist(),
                       is_label_show=True,
                       is_stack=True,
                       center=[75, 50])
            Grid_chart2.add(chart3, f'{year}年{month}月')
        page.add(Grid_chart1)
        page.add(Grid_chart2)
        page.render(os.path.join(BASE_DIR, 'templates/{}'.format(path)))
예제 #13
0
    def form_valid(self, form):

        line1 = Line()
        val1 = services.line(form.cleaned_data['code1'],
                             form.cleaned_data['start'],
                             form.cleaned_data['end'],
                             form.cleaned_data['col1'],
                             form.cleaned_data['is_index1'])

        line1.add(services.code_str(form.cleaned_data['code1']),
                  list(val1.keys()), list(val1.values()))

        line2 = Line()
        val2 = services.line(form.cleaned_data['code2'],
                             form.cleaned_data['start'],
                             form.cleaned_data['end'],
                             form.cleaned_data['col2'],
                             form.cleaned_data['is_index2'])
        line2.add(services.code_str(form.cleaned_data['code2']),
                  list(val2.keys()), list(val2.values()))

        overlap = Overlap(
            '%s-%s' % (form.cleaned_data['start'], form.cleaned_data['end']))
        overlap.add(line1)
        overlap.add(line2, yaxis_index=1, is_add_yaxis=True)

        return show(self.request, overlap)
예제 #14
0
파일: echart.py 프로젝트: onecans/my
def show_overview_day(category, method, name):

    # if not _check_category(category):

    index_data = services.line(indexs.get(category, '999999'),
                               'start',
                               'end',
                               col='high')
    se_data = services.se(method[4:], category)

    df1 = pd.DataFrame.from_dict(index_data)
    df1.index = pd.DatetimeIndex(df1.index)

    df2 = pd.DataFrame.from_dict(se_data)
    df2.index = pd.DatetimeIndex(df2.index)

    df1, df2 = reindex2([df1, df2])
    print(df1)
    print(df2)
    line1 = Line()
    line1.add(name, df2.index, df2[category.upper()], is_datazoom_show=False)
    line2 = Line()
    line2.add('index: %s' % indexs.get(category, '999999'),
              df1.index,
              df1['high'],
              is_datazoom_show=True)

    overlap = Overlap()
    overlap.add(line1)
    # 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1
    # 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变

    overlap.add(line2, yaxis_index=1, is_add_yaxis=True)
    return overlap
예제 #15
0
def strategy():

    form = request.form
    getStock = form.get('stock')
    stock = getStock if getStock else "usTSLA"

    getCircle = form.get('circle')
    circle = getCircle if getCircle else "120"

    buyStrategy = BuyTrendStrategy(stock, int(circle), 1000000)
    closeDayList, closeValueList = buyStrategy.get_close_line()
    buyDayList, buyValueList = buyStrategy.get_buy_point()

    closeLine = Line("趋势购买策略", width="400", height="300")
    closeLine.add(stock, closeDayList, closeValueList)

    buyES = EffectScatter("购买点", width="400", height="300")
    buyES.add("购买点",
              buyDayList,
              buyValueList,
              symbol_size=8,
              effect_scale=3,
              effect_period=3,
              symbol="triangle")

    overlap = Overlap()
    overlap.add(closeLine)
    overlap.add(buyES)

    return render_template(
        "strategy.html",
        strategyEchart=overlap.render_embed(),
        host=REMOTE_HOST,
        script_list=buyES.get_js_dependencies(),
    )
예제 #16
0
def plot_days_to_trend(video_df, save_filename):
    """
    使用 pyecharts 统计视频发布后上榜的天数
    :param
            - video_df:
            - save_filename:
    """
    video_df['diff'] = (video_df['trending_date'] - video_df['publish_time']).dt.days
    days_df = video_df['diff'].value_counts()

    # 观察视频发布后2个月的情况
    days_df = days_df[(days_df.index >= 0) & (days_df.index <= 60)]
    days_df = days_df.sort_index()

    bar = Bar('视频发布后2个月的情况')
    bar.add(
        '柱状图', days_df.index.tolist(), days_df.values.tolist(),
        is_datazoom_show=True,  # 启用数据缩放功能
        datazoom_range=[0, 50]  # 百分比范围
    )

    line = Line()
    line.add('折线图', days_df.index.tolist(), days_df.values.tolist())

    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)
    overlap.render(os.path.join(config.output_path, save_filename))
예제 #17
0
def generate_score_tabale():
    city_main = city_com.sort_values('count', ascending=False)[0:20]
    attr = city_main['city']
    v1 = city_main['count']
    v2 = city_main['mean']
    line = Line("主要城市平均评分")
    line.add("主要城市平均评分",
             attr,
             v2,
             is_stack=True,
             xaxis_rotate=50,
             yaxis_min=4.0,
             mark_point=['min', 'max'],
             xaxis_interval=0,
             line_color='lightblue',
             line_width=4,
             mark_point_textcolor='yellow',
             mark_point_color='lightblue',
             is_splitline_show=False)

    bar = Bar("主要城市评论数及评分")
    bar.add("主要城市评论数",
            attr,
            v1,
            is_stack=True,
            xaxis_rotate=50,
            yaxis_min=0,
            xaxis_interval=0,
            is_splitline_show=False)
    overlap = Overlap()
    # 默认不新增 x y 轴,并且 x y 轴的索引都为 0
    overlap.add(bar)
    overlap.add(line, yaxis_index=1, is_add_yaxis=True)
    overlap.render('resources/city_score.html')
예제 #18
0
파일: score.py 프로젝트: lyyhui1314/score
def view(numList):
    line = Line('折线图', width=2000)
    atter = ['数据异常', '不及格', '及格', '良好', '优秀', '满分']
    v1 = [numList[0], numList[1], numList[2], numList[3], numList[4], numList[5]]
    line.add('最高成绩', atter, v1,
             mark_point=['max'],  # 标点最大值
             mark_line=['average'])  # 虚线位置是平均分
    line.add('最低成绩', atter, v1,
             mark_point=['min'],
             legend_pos='20%')
    es = EffectScatter()  # 调用闪烁点
    es.add('', atter, v1, effect_scale=8)
    # 调用合并函数,再一个图表上输出
    overlop = Overlap()
    overlop.add(line)
    overlop.add(es)

    pie = Pie('饼图', title_pos='80%')
    pie.add('', atter, v1,
            radius=[60, 30],  # 控制内外半径的
            center=[65, 50],
            legend_pos='80%',
            legend_orient='vertical')
    # 显示两个示例图的调用函数,不然会覆盖
    grid = Grid()
    grid.add(overlop, grid_right='50%')
    grid.add(pie, grid_left='60%')
    grid.render('abc.html')
예제 #19
0
def brush(data):
    data = hist_sum(data)
    kline = Kline()
    kline.add(
        'Kline',
        data.index,
        data.loc[:, ['open', 'close', 'low', 'high']].values,
        mark_line=['max', 'min'],
        mark_line_valuedim=['highest', 'lowest'],
        is_datazoom_show=True,
        datazoom_xaxis_index=[0, 1],
    )
    brush = Line()
    brush.add(
        'Brush',
        data.index,
        data.endpoint.values,
    )
    overlap = Overlap()
    overlap.add(kline)
    overlap.add(brush)

    macd = Bar()
    macd.add(
        'MACD',
        data.index,
        data.hist_sum.values,
    )
    page = Page()
    page.add(overlap)
    page.add(macd)
    return page
예제 #20
0
	def na_timeline(dff,column,time_col,time_type=None):
		# time_col should be format like 'yyyy-mm-dd', such as '2018-01-17'
		df = dff.copy()
		df['na']=df[df[column].columns.values.tolist()].T.count()
		df['na'] = df['na'].map(lambda x: 1 if x>0 else np.nan)
		if time_type == 'timestamp':
			df[time_col] = df[time_col].map(lambda x: datetime.datetime.fromtimestamp(x).strftime("%Y-%m-%d"))
		elif time_type == 'time_str':
			df[time_col] = df[time_col].map(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d"))
		else:
			df[time_col] = df[time_col].map(lambda x: x.strftime("%Y-%m-%d"))
		attr = df[[time_col]+column].groupby(time_col).size().index.tolist()
		v1 = df[[time_col]+column+['na']].groupby(time_col).size().values.tolist()
		v2 = (np.round(100-df[[time_col]+['na']].groupby(time_col).count()['na'].values.tolist()/df[[time_col]+column+['na']].groupby(time_col).size()*100)).values.tolist()
		bar = Bar(width=1200, height=600,title='NA Timeline')
		bar.add("数量", attr, v1,is_stack=True,is_datazoom_show=True,datazoom_type='both',datazoom_range=[0,100],
					label_color=['#0081FF','#FF007C'],is_visualmap=True, visual_type='size',visual_range=[0,100],
					visual_range_size=[10,10],is_yaxislabel_align=False,visual_dimension=1,tooltip_text_color='#000000',
					label_emphasis_textcolor='#000000',is_more_utils=True)
		line = Line()
		line.add('缺失率', attr, v2, yaxis_formatter="%", yaxis_min=0,yaxis_max=100,label_emphasis_textcolor='#000000',
				 mark_line=['average'],line_width=3)
		overlap = Overlap()
		overlap.add(bar)
		overlap.add(line, yaxis_index=1, is_add_yaxis=True)
		return overlap
예제 #21
0
 def kline_plot(self,ktype=0):
     df=self.cal_hadata()
     #画K线图数据
     date = df.index.strftime('%Y%m%d').tolist()
     if ktype==0:
         k_value = df[['open','close', 'low','high']].values
     else:
         k_value = df[['ha_open','ha_close', 'ha_low', 'ha_high']].values
     #引入pyecharts画图使用的是0.5.11版本,新版命令需要重写
     
     kline = Kline(self.name+'行情走势')
     kline.add('日K线图', date, k_value,
           is_datazoom_show=True,is_splitline_show=False)
     #加入5、20日均线
     df['ma20']=df.close.rolling(20).mean()
     df['ma5']=df.close.rolling(5).mean()
     line = Line()
     v0=df['ma5'].round(2).tolist()
     v=df['ma20'].round(2).tolist()
     line.add('5日均线', date,v0,
          is_symbol_show=False,line_width=2)
     line.add('20日均线', date,v, 
          is_symbol_show=False,line_width=2)
     #成交量
     bar = Bar()
     bar.add('成交量', date, df['vol'],tooltip_tragger='axis', 
             is_legend_show=False, is_yaxis_show=False, 
             yaxis_max=5*max(df['vol']))
     overlap = Overlap()
     overlap.add(kline)
     overlap.add(line,)
     overlap.add(bar,yaxis_index=1, is_add_yaxis=True)
     return overlap
예제 #22
0
def name_trend(name, data, gender=['M','F'], year=1920, dodge = 500):
    if isinstance(gender, str):
        name_data = data[(data['Name'] == name)&(data['Gender']==gender)&(data['Year']>=year)]
        attr = list(name_data['Year'].values)
        attr1=list(map(str,attr))
        bar = Bar("名人名字的影响",width=1000, height=600)
        bar.add(name, attr, list(name_data['Count'].values), mark_line=["average"], mark_point=["max", "min"],
               legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18)
        line = Line()
        line.add(name, attr1, list(name_data['Count'].values + dodge))
        
    else:
        name_data = data[(data['Name'] == name)&(data['Year']>=year)]
        attr = list(range(year, 2018))
        attr1=list(map(str,attr))
        v1 = name_data[name_data['Gender']==gender[0]].Count.values
        v2 = name_data[name_data['Gender']==gender[1]].Count.values
        bar = Bar("名人名字的影响",width=1000, height=600)
        bar.add(name+"男", attr, list(v1), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18)
        bar.add(name+"女", attr, list(v2), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18)
        line = Line()
        line.add(name+"男", attr1, list(v1 + dodge))
        line.add(name+"女", attr1, list(v2 + dodge))
    
    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)
    page.add(overlap)
예제 #23
0
def get_chatrs(train, col):
    data = train.groupby([col])['Attrition']
    data_sum = data.sum()  # 离职人数
    data_mean = data.mean()  # 离职率

    bar = Bar(col, title_pos="45%")
    bar.add('离职人数',
            data_sum.index,
            data_sum.values,
            mark_point=['max'],
            yaxis_formatter='人',
            yaxis_max=200,
            legend_pos="40%",
            legend_orient="vertical",
            legend_top="95%",
            bar_category_gap='25%')

    line = Line()
    line.add('离职率',
             data_mean.index,
             data_mean.values,
             mark_point=['max'],
             mark_line=['average'],
             yaxis_max=0.8)

    overlap = Overlap(width=900, height=400)
    overlap.add(bar)
    overlap.add(line, is_add_yaxis=True, yaxis_index=1)

    return overlap
예제 #24
0
 def MACD(self):
     dif, dea, macd = self.__macd()
     overlap = Overlap()
     macdBar = Bar()
     macdBar.add("",
                 self.__date,
                 macd,
                 is_datazoom_show=True,
                 is_visualmap=True,
                 is_piecewise=True,
                 pieces=[
                     {
                         'min': 0,
                         'max': 300,
                         'color': "#f47920"
                     },
                     {
                         'min': -300,
                         'max': 0,
                         'color': "#f6f5ec"
                     },
                 ])
     macdline = Line()
     macdline.add("", self.__date, dif, is_smooth=False)
     macdline.add("", self.__date, dea, is_smooth=False)
     overlap.add(macdBar)
     overlap.add(macdline)
     return overlap
예제 #25
0
def assets_curve(dates, sum):
    xs = dates
    ys = sum
    xs_date = [x.date() for x in xs]

    line = Line("盈利走势图")
    line.add("盈利",
             xs_date,
             sum,
             is_smooth=True,
             mark_line=["min", "max", "average"],
             mark_point=[
                 'min', 'max', 'average', {
                     "coord": [xs_date[-1], ys[-1]],
                     "name": "now"
                 }
             ],
             is_datazoom_show=True,
             xaxis_name="时间",
             yaxis_name="元",
             tooltip_trigger="axis")

    overlap = Overlap(width=1200, height=600)
    # 默认不新增 x y 轴,并且 x y 轴的索引都为 0
    overlap.add(line)
    overlap.render('profit.html')
def forecastPlot(foreData, target, localPath):
    """
    :param ismn_data: DataFrame. Merged dataset of ISMN
    :return: html file stored in paht './plot/ismn_ts'
    """
    # create a new folder: plot/ismn_ts
    path = '../{}/predictionPlot'.format(localPath)
    if not os.path.exists(path):
        os.makedirs(path)
    foreData = foreData.copy()
    foreData['timeStamp'] = pd.to_datetime(foreData['timeStamp'])

    for station in foreData.station.unique():
        line = Line("forecast of soil mosture at %i cm" % target, station)
        overlap = Overlap(width=1200, height=500)
        dataset = foreData[foreData.station == station]
        dataset.index = dataset.timeStamp

        fore_columns = list(dataset.filter(regex='fore|actual').columns)
        for forecastVar in fore_columns:
            x = dataset.index
            y = list(dataset.loc[:, [forecastVar]].values.reshape(-1))
            line.add(forecastVar, x, y, is_datazoom_show=True)

        overlap.add(line)
        overlap.render(path=path +
                       '/{0}_forecast_{1}cm.html'.format(station, target))
예제 #27
0
def loc_and_mean_age(info):
    grouped = group(info, ['cityChn'])
    tidy = grouped['age']
    tidy_com = tidy.agg(['mean', 'count'])
    tidy_com.reset_index(inplace=True)
    tidy_com['mean'] = round(tidy_com['mean'], 2)

    attr = tidy_com['cityChn']
    num = tidy_com['count']
    aver = tidy_com['mean']

    line = Line("小姐姐-平均年龄")
    line.add("年龄",
             attr,
             aver,
             is_stack=True,
             xaxis_rotate=30,
             mark_point=['max', 'min'],
             yaxis_min=26,
             is_splitline_show=False)

    bar = Bar("小姐姐-城区分布")
    bar.add("单位:人",
            attr,
            num,
            mark_point=['max'],
            mark_line=['average'],
            xaxis_rotate=30,
            yaxis_min=0)

    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line, yaxis_index=1, is_add_yaxis=True)
    overlap.render("北京百合小姐姐平均年龄与分布.html")
예제 #28
0
def name_trend(name, data, gender=['M','F'], year=1920, dodge = 500):
    if isinstance(gender, str):
        name_data = data[(data['Name'] == name)&(data['Gender']==gender)&(data['Year']>=year)]
        attr = list(name_data['Year'].values)
        bar = Bar(name)
        bar.add("", attr, list(name_data['Count'].values), mark_line=["average"], mark_point=["max", "min"],
               legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18)
        line = Line()
        line.add("", attr, list(name_data['Count'].values + dodge))
        
    else:
        name_data = data[(data['Name'] == name)&(data['Year']>=year)]
        attr = list(range(year, 2018))
        v1 = name_data[name_data['Gender']==gender[0]].Count.values
        v2 = name_data[name_data['Gender']==gender[1]].Count.values
        bar = Bar(name)
        bar.add("男", attr, list(v1), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18)
        bar.add("女", attr, list(v2), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18)
        line = Line()
        line.add("", attr, list(v1 + dodge))
        line.add("", attr, list(v2 + dodge))
    
    overlap = Overlap()
    overlap.add(bar)
    overlap.add(line)
    return overlap.render(str(name)+str(gender)+str(dodge)+'.html')
예제 #29
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()
예제 #30
0
def show_charts(error_data, last_time):
    charts_data = error_data.copy()
    charts_data.pop("null_name")
    codes = [v[0] for k, v in charts_data.items() if len(v) != 0]
    print(codes)

    if len(codes) > 0:
        page = Page()
        limit = minutes.index(last_time) + 1
        mins = [str(x)[:-2] + ":" + str(x)[-2:] for x in minutes[:limit]]
        for code in codes:
            print(code)
            pipeline4 = [{
                "$unwind": "$data"
            }, {
                "$match": {
                    "_id": code
                }
            }, {
                "$limit": limit
            }]
            stks_data = table.aggregate(pipeline4)
            price = []
            avg_px = []
            chg_pct = []
            for stk in stks_data:
                price.append(round(stk["data"]["current_px"], 2))
                avg_px.append(round(stk["data"]["avg_px"], 2))
                chg_pct.append(stk["data"]["chg_pct"])

            last_value = min(price + avg_px)

            line = Line(code)
            line.add("cur_price",
                     mins,
                     price,
                     yaxis_min=last_value,
                     tooltip_axispointer_type='cross',
                     is_smooth=True)
            line.add("avg_price",
                     mins,
                     avg_px,
                     yaxis_min=last_value,
                     tooltip_axispointer_type='cross',
                     is_smooth=True)

            line1 = Line()
            line1.add("chg_pct",
                      mins,
                      chg_pct,
                      tooltip_axispointer_type='cross',
                      is_smooth=True,
                      yaxis_formatter="%")

            overlap = Overlap()
            overlap.add(line)
            overlap.add(line1, yaxis_index=1, is_add_yaxis=True)
            page.add(line)
        page.render(u"html\\" + str(last_time) + ".html")