Ejemplo n.º 1
0
def kline(stock_data: pd.DataFrame):
    """
    @input: column name ('date', 'open', 'close', 'min', 'max', 'Trading_Volume')
    """
    def calculate_ma(day_count: int, price: list):
        result: List[Union[float, str]] = []
        for i in range(len(price)):
            if i < day_count:
                result.append("-")
                continue
            sum_total = 0.0
            for j in range(day_count):
                sum_total += float(price[i - j])
            result.append(abs(float("%.3f" % (sum_total / day_count))))
        return result

    def process_stock_data(data):
        data = data[["date", "open", "close", "min", "max", "Trading_Volume"]]
        data.columns = ["date", "open", "close", "low", "high", "volume"]
        if is_datetime(data["date"]):
            data_times = data["date"].dt.strftime("%Y-%m-%d").to_list()
        else:
            data_times = data["date"].to_list()
        values = data.values.tolist()
        volumes = []
        for i, tick in enumerate(data.values.tolist()):
            volumes.append([i, tick[5], 1 if tick[1] > tick[2] else -1])
        return {
            "categoryData": data_times,
            "values": values,
            "volumes": volumes,
        }

    chart_data = process_stock_data(stock_data)

    kline_data = [data[1:-1] for data in chart_data["values"]]
    kline = Kline(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts(
        animation=False), ))
    kline.add_xaxis(xaxis_data=chart_data["categoryData"])
    kline.add_yaxis(
        series_name="kline",
        y_axis=kline_data,
        itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"),
    )
    kline.set_global_opts(
        legend_opts=opts.LegendOpts(is_show=True, pos_left="center"),
        datazoom_opts=[
            opts.DataZoomOpts(
                is_show=False,
                type_="inside",
                xaxis_index=[0, 1],
                range_start=85,
                range_end=100,
            ),
            opts.DataZoomOpts(
                is_show=True,
                xaxis_index=[0, 1],
                type_="slider",
                pos_top="85%",
                range_start=85,
                range_end=100,
            ),
        ],
        yaxis_opts=opts.AxisOpts(
            is_scale=True,
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),
        ),
        tooltip_opts=opts.TooltipOpts(
            trigger="axis",
            axis_pointer_type="cross",
            background_color="rgba(245, 245, 245, 0.8)",
            border_width=1,
            border_color="#ccc",
            textstyle_opts=opts.TextStyleOpts(color="#000"),
        ),
        visualmap_opts=opts.VisualMapOpts(
            is_show=False,
            dimension=2,
            series_index=5,
            is_piecewise=True,
            pieces=[
                {
                    "value": 1,
                    "color": "#00da3c"
                },
                {
                    "value": -1,
                    "color": "#ec0000"
                },
            ],
        ),
        axispointer_opts=opts.AxisPointerOpts(
            is_show=True,
            link=[{
                "xAxisIndex": "all"
            }],
            label=opts.LabelOpts(background_color="#777"),
        ),
        brush_opts=opts.BrushOpts(
            x_axis_index="all",
            brush_link="all",
            out_of_brush={"colorAlpha": 0.1},
            brush_type="lineX",
        ),
    )

    close = np.array(chart_data["values"])[:, 2]
    ma_items = [5, 10, 20, 60]

    line = Line(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts(
        animation=False), )).add_xaxis(xaxis_data=chart_data["categoryData"])
    for ma in ma_items:
        line.add_yaxis(
            series_name="MA" + str(ma),
            y_axis=calculate_ma(day_count=ma, price=close),
            is_smooth=True,
            is_symbol_show=False,
            is_hover_animation=False,
            linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5),
            label_opts=opts.LabelOpts(is_show=False),
        )
    line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))

    bar = Bar(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts(
        animation=False), ))
    bar.add_xaxis(xaxis_data=chart_data["categoryData"])
    bar.add_yaxis(
        series_name="Volume",
        y_axis=chart_data["volumes"],
        xaxis_index=1,
        yaxis_index=1,
        label_opts=opts.LabelOpts(is_show=False),
    )

    bar.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            is_scale=True,
            grid_index=1,
            boundary_gap=False,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=False),
            split_number=20,
            min_="dataMin",
            max_="dataMax",
        ),
        yaxis_opts=opts.AxisOpts(
            grid_index=1,
            is_scale=True,
            split_number=2,
            axislabel_opts=opts.LabelOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_show=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    )

    overlap_kline_line = kline.overlap(line)

    grid_chart = Grid(init_opts=opts.InitOpts(
        width="1000px",
        height="800px",
        animation_opts=opts.AnimationOpts(animation=False),
    ))
    grid_chart.add(
        overlap_kline_line,
        grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", height="50%"),
    )
    grid_chart.add(
        bar,
        grid_opts=opts.GridOpts(pos_left="10%",
                                pos_right="8%",
                                pos_top="63%",
                                height="16%"),
    )
    grid_chart.render("kline.html")
    display(HTML(filename="kline.html"))
    return grid_chart
Ejemplo n.º 2
0
def bar_same_series_gap() -> Bar:
    c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
        "商家A", Faker.values(), category_gap="80%").set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-单系列柱间距离")))
    return c
Ejemplo n.º 3
0
def bar_base() -> Bar:
    c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
        "商家A",
        Faker.values()).add_yaxis("商家B", Faker.values()).set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")))
    return c
Ejemplo n.º 4
0
from pyecharts.charts import Bar  # 柱状图对象
from pyecharts import options  # 配置对象
from pyecharts.globals import ThemeType
# 创建柱状图对象
(Bar({'theme': ThemeType.DARK})
 # 添加横坐标
 .add_xaxis(["冰箱", "洗衣机", "彩电", "空调", "电脑", "电饭煲"])
 # 添加纵坐标(数据)可以添加多个
 .add_yaxis("格力", [100, 200, 250, 150, 50, 300],
            stack="strack").add_yaxis("小米", [200, 100, 50, 150, 240, 180],
                                      stack="strack")
 # 创建标题对象
 .set_global_opts(
     title_opts=options.TitleOpts(title="家电销售情况"),
     # visualmap_opts=options.VisualMapOpts(max_=200), # 设置阈值
     datazoom_opts=[options.DataZoomOpts()],  # 拉的进度条
     brush_opts=options.BrushOpts(),  # 工具栏
     yaxis_opts=options.AxisOpts(name="y轴名字"),
     xaxis_opts=options.AxisOpts(name="x轴名字"),
 ).render("家电柱状图.html"))
Ejemplo n.º 5
0
def bar_is_selected() -> Bar:
    c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
        "商家A", Faker.values()).add_yaxis(
            "商家B", Faker.values(), is_selected=False).set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-默认取消显示某 Series")))
    return c
Ejemplo n.º 6
0
datas = cursor.fetchall()
china_sql = 'select * from china_count'
cursor.execute(china_sql)
china_data = cursor.fetchone()
# 地图
map_obj = (
    Map()
        .add("", datas, "china")
        .set_global_opts(
        title_opts=opts.TitleOpts(title="疫情情况", subtitle="截止目前为止,全国共有累计确诊{}例,累计治愈{}例,累计死亡{}例,疑似{}例"
                                  .format(china_data[0], china_data[1], china_data[2], china_data[3])
                                  ),
        visualmap_opts=opts.VisualMapOpts(max_=3),
    )
)
name_list = [name[0] for name in datas]
data_list = [name[1] for name in datas]
# 柱状图
bar_obj = (
    Bar()
        .add_xaxis(name_list)
        .add_yaxis("各省份数据对比", data_list)
        .set_global_opts(title_opts=opts.TitleOpts(title="各省份目前情况"),
                         datazoom_opts=[opts.DataZoomOpts()]
                         )
)
# page对象用于整合地图
p = Page(layout=Page.SimplePageLayout)
p.add(map_obj, bar_obj)
p.render("疫情实时监控.html")
Ejemplo n.º 7
0
def generate_price_bar_html(rows, title):
    xx1 = []
    xx2 = []
    yy1 = []
    yy2 = []

    count = 0
    for row in rows:
        bond_code = row[0]
        bond_code = trade_utils.rebuild_bond_code(bond_code)
        count += 1
        if count <= 20:
            xx1.append(row[1].replace('转债', ''))
            yy1.append({
                'value': row[2],
                'bond_code': bond_code,
                'rise': row[3],
                'premium': row[4]
            })
        else:
            xx2.insert(0, row[1].replace('转债', ''))
            yy2.insert(
                0, {
                    'value': round(-float(row[2]) + 0, 2),
                    'bond_code': bond_code,
                    'rise': row[3],
                    'premium': row[4]
                })

    max_value = 0
    size = len(yy1)

    for i in range(size):
        if yy1[i]['value'] + abs(yy2[i]['value']) > max_value:
            max_value = yy1[i]['value'] + abs(yy2[i]['value'])

    max_value = round(max_value * 0.7, 2) + 1

    chart_id = str(abs(hash(title)))
    bar = Bar(init_opts=opts.InitOpts(height='700px',
                                      width='1424px',
                                      theme=ThemeType.SHINE,
                                      chart_id=chart_id))

    add_popwin_js_code(bar, chart_id)

    # 底部x轴
    bar.add_xaxis(xx1)
    # 顶部x轴
    bar.extend_axis(
        xaxis_data=xx2,
        xaxis=opts.AxisOpts(type_="category",
                            position='top',
                            axislabel_opts=opts.LabelOpts(rotate=-60, )),
    )
    # 右侧y轴
    bar.extend_axis(yaxis=opts.AxisOpts(
        type_="value",
        position="right",
        name='可转债价格(元)',
        name_gap=45,
        name_location='middle',
        min_=-max_value,
        is_scale=True,
        axisline_opts=opts.AxisLineOpts(
            linestyle_opts=opts.LineStyleOpts(is_show=True, )),
        # axislabel_opts=opts.LabelOpts(formatter="{value}"),
        axislabel_opts=opts.LabelOpts(
            formatter=JsCode("function(x){return (x + '元').substring(1);}")),
    ))
    # 添加高价格的柱状图
    bar.add_yaxis(
        "高价格",
        yy1,
        bar_width=25,
        category_gap='1%',
        gap='1%',
        label_opts=opts.LabelOpts(
            is_show=True,
            position="top",
            formatter=JsCode("function(x){return x.data['value']+'元';}")),
    )
    # 添加低价格的柱状图
    bar.add_yaxis(
        "低价格",
        yy2,
        bar_width=25,
        yaxis_index=1,
        label_opts=opts.LabelOpts(
            is_show=True,
            position="bottom",
            formatter=JsCode(
                "function(x){return (x.data['value'] + '元').substring(1);}")),
    )
    # bar.reversal_axis()
    bar.set_series_opts(
        # itemstyle_opts=opts.ItemStyleOpts(
        #     color=JsCode(
        #         "function(x){return x.data['value']>0?'#c23531':'#1d953f'}"
        #     )
        # )
    )
    bar.set_global_opts(
        title_opts=opts.TitleOpts(
            title="=========" + title + "=========",
            pos_left='center',
            pos_top='-1px',
        ),
        tooltip_opts=opts.TooltipOpts(
            is_show=True,
            formatter=JsCode(
                "function (params){return '名&nbsp;&nbsp;&nbsp;称: ' + params.name + '<br/>' + '涨&nbsp;&nbsp;&nbsp;跌: ' + params.data['rise'] + '%<br/>' + '溢价率: ' + params.data['premium']}"
            )),
        legend_opts=opts.LegendOpts(is_show=False),
        xaxis_opts=opts.AxisOpts(
            # data=None,
            # type_='category',
            # name_gap=0,
            # name_rotate=90,
            axislabel_opts=opts.LabelOpts(rotate=-60, ),
            is_scale=True,
            name_location='middle',
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_on_zero=True,
                                            # symbol=['none', 'arrow']
                                            )),
        yaxis_opts=opts.AxisOpts(
            type_='value',
            name='可转债价格(元)',
            # name_rotate=90,
            name_gap=35,
            name_location='middle',
            # min_=0,
            max_=max_value,
            is_scale=True,
            axislabel_opts=opts.LabelOpts(formatter='{value}元'),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_on_zero=False,
                                            # symbol=['none', 'arrow']
                                            )),
    )

    bar_html = bar.render_embed('template.html', html_utils.env)
    return bar_html
import streamlit.components.v1 as components
from pyecharts import options as opts
from pyecharts.charts import Bar

c = (
    Bar().add_xaxis(
        ["Microsoft", "Amazon", "IBM",
         "Oracle", "Google", "Alibaba"]).add_yaxis(
             '2017-2018 Revenue in (billion $)',
             [21.2, 20.4, 10.3, 6.08, 4, 2.2]).set_global_opts(
                 title_opts=opts.TitleOpts(title="Top cloud providers 2018",
                                           subtitle="2017-2018 Revenue"),
                 toolbox_opts=opts.ToolboxOpts()).render_embed(
                 )  # generate a local HTML file
)
components.html(c, width=1000, height=1000)
Ejemplo n.º 9
0
def get_bar_data(request):
    x_field = request.GET.get('x_choice')
    y_field = request.GET.get('y_choice')
    print(request.GET.get('begin_date'))
    start_date = request.GET.get('begin_date').split('-')
    end_date = request.GET.get('end_date').split('-')
    start = datetime.date(int(start_date[0]), int(start_date[1]),
                          int(start_date[2]))
    end = datetime.date(int(end_date[0]), int(end_date[1]), int(end_date[2]))
    y_lists = []
    x_list = []
    b = Bar()
    if x_field == 'street' and y_field == 'property':
        event_counts = Street.objects.all().values(
            'name', 'number').order_by('-number')
        for property in properties:
            new_list = [property.name]
            for street_node in event_counts:
                new_len = 0
                street = Street.objects.get(name=street_node['name'])
                for community in Community.objects.filter(street=street):
                    new_len += len(
                        Event.objects.filter(community=community,
                                             property=property,
                                             create_time__range=(start, end)))
                new_list.append(new_len)
                # print(new_list)
            y_lists.append(new_list)
        for street_node in event_counts:
            x_list.append(street_node['name'])

    elif x_field == 'community' and y_field == 'property':
        event_counts = Community.objects.all().values(
            'name', 'number').order_by('-number')
        for property in properties:
            new_list = [property.name]
            for street_node in event_counts:
                community = Community.objects.get(name=street_node['name'])
                new_len = len(
                    Event.objects.filter(
                        Q(create_time__range=(start, end))
                        & Q(community=community) & Q(property=property)))
                new_list.append(new_len)
                # print(new_list)
            y_lists.append(new_list)
        for community_node in event_counts:
            x_list.append(community_node['name'])

    elif x_field == 'dispose_unit' and y_field == 'property':
        event_counts = DisposeUnit.objects.all().values(
            'name', 'number').order_by('-number')
        for property in properties:
            new_list = [property.name]
            limit = 0
            for dispose_unit_node in event_counts:
                dispose_unit = DisposeUnit.objects.get(
                    name=dispose_unit_node['name'])
                if limit < 30:
                    new_len = len(
                        Event.objects.filter(
                            Q(create_time__range=(start, end))
                            & Q(dispose_unit=dispose_unit)
                            & Q(property=property)))
                    new_list.append(new_len)
                    new_len = 0
                else:
                    new_len += len(
                        Event.objects.filter(
                            Q(create_time__range=(start, end))
                            & Q(dispose_unit=dispose_unit)
                            & Q(property=property)))
                limit += 1
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for dispose_unit_node in event_counts:
            if limit >= 30:
                break
            x_list.append(dispose_unit_node['name'])
            limit += 1
        x_list.append("其他")

    elif x_field == 'main_type' and y_field == 'property':
        event_counts = MainType.objects.all().values(
            'name', 'number').order_by('-number')
        for property in properties:
            new_list = [property.name]
            limit = 0
            new_len = 0
            for main_type_node in event_counts:
                main_type = MainType.objects.get(name=main_type_node['name'])
                for sub_type in SubType.objects.filter(main_type=main_type):
                    new_len += len(
                        Event.objects.filter(sub_type=sub_type,
                                             property=property,
                                             create_time__range=(start, end)))
                if limit < 30:
                    limit += 1
                    new_list.append(new_len)
                    new_len = 0
                # print(new_list)
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for main_type_node in event_counts:
            if limit >= 30:
                break
            x_list.append(main_type_node['name'])
            limit += 1
        x_list.append('其他')

    elif x_field == 'sub_type' and y_field == 'property':
        event_counts = SubType.objects.all().values(
            'name', 'number').order_by('-number')
        for property in properties:
            new_list = [property.name]
            limit = 0
            new_len = 0
            for sub_type_node in event_counts:
                sub_type = SubType.objects.get(name=sub_type_node['name'])
                new_len += len(
                    Event.objects.filter(
                        Q(create_time__range=(start, end))
                        & Q(property=property) & Q(sub_type=sub_type)))
                if limit < 60:
                    limit += 1
                    new_list.append(new_len)
                    new_len = 0
                # print(new_list)
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for sub_type_node in event_counts:
            if limit >= 60:
                break
            x_list.append(sub_type_node['name'])
            limit += 1
        x_list.append('其他')

    elif x_field == 'street' and y_field == 'achieve':
        event_counts = Street.objects.all().values(
            'name', 'number').order_by('-number')
        for achieve in achieves:
            new_list = [achieve.name]
            for street_node in event_counts:
                new_len = 0
                street = Street.objects.get(name=street_node['name'])
                for community in Community.objects.filter(street=street):
                    new_len += len(
                        Event.objects.filter(community=community,
                                             achieve=achieve,
                                             create_time__range=(start, end)))
                new_list.append(new_len)
                # print(new_list)
            y_lists.append(new_list)
        for street_node in event_counts:
            x_list.append(street_node['name'])

    elif x_field == 'community' and y_field == 'achieve':
        event_counts = Community.objects.all().values(
            'name', 'number').order_by('-number')
        for achieve in achieves:
            new_list = [achieve.name]
            for street_node in event_counts:
                community = Community.objects.get(name=street_node['name'])
                new_len = len(
                    Event.objects.filter(
                        Q(create_time__range=(start, end))
                        & Q(community=community) & Q(achieve=achieve)))
                new_list.append(new_len)
                # print(new_list)
            y_lists.append(new_list)
        for community_node in event_counts:
            x_list.append(community_node['name'])

    elif x_field == 'dispose_unit' and y_field == 'achieve':
        event_counts = DisposeUnit.objects.all().values(
            'name', 'number').order_by('-number')
        for achieve in achieves:
            new_list = [achieve.name]
            limit = 0
            for dispose_unit_node in event_counts:
                dispose_unit = DisposeUnit.objects.get(
                    name=dispose_unit_node['name'])
                if limit < 30:
                    new_len = len(
                        Event.objects.filter(
                            Q(create_time__range=(start, end))
                            & Q(dispose_unit=dispose_unit)
                            & Q(achieve=achieve)))
                    new_list.append(new_len)
                    new_len = 0
                else:
                    new_len += len(
                        Event.objects.filter(
                            Q(create_time__range=(start, end))
                            & Q(dispose_unit=dispose_unit)
                            & Q(achieve=achieve)))
                limit += 1
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for dispose_unit_node in event_counts:
            if limit >= 30:
                break
            x_list.append(dispose_unit_node['name'])
            limit += 1
        x_list.append("其他")

    elif x_field == 'main_type' and y_field == 'achieve':
        event_counts = MainType.objects.all().values(
            'name', 'number').order_by('-number')
        for achieve in achieves:
            new_list = [achieve.name]
            limit = 0
            new_len = 0
            for main_type_node in event_counts:
                main_type = MainType.objects.get(name=main_type_node['name'])
                for sub_type in SubType.objects.filter(main_type=main_type):
                    new_len += len(
                        Event.objects.filter(sub_type=sub_type,
                                             achieve=achieve,
                                             create_time__range=(start, end)))
                if limit < 30:
                    limit += 1
                    new_list.append(new_len)
                    new_len = 0
                # print(new_list)
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for main_type_node in event_counts:
            if limit >= 30:
                break
            x_list.append(main_type_node['name'])
            limit += 1
        x_list.append('其他')

    elif x_field == 'sub_type' and y_field == 'achieve':
        event_counts = SubType.objects.all().values(
            'name', 'number').order_by('-number')
        for achieve in achieves:
            new_list = [achieve.name]
            limit = 0
            new_len = 0
            for sub_type_node in event_counts:
                sub_type = SubType.objects.get(name=sub_type_node['name'])
                new_len += len(
                    Event.objects.filter(
                        Q(create_time__range=(start, end)) & Q(achieve=achieve)
                        & Q(sub_type=sub_type)))
                if limit < 60:
                    limit += 1
                    new_list.append(new_len)
                    new_len = 0
                # print(new_list)
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for sub_type_node in event_counts:
            if limit >= 60:
                break
            x_list.append(sub_type_node['name'])
            limit += 1
        x_list.append('其他')

    b.add_xaxis(x_list)
    for y_list in y_lists:
        b.add_yaxis(y_list[0], y_list[1:], stack="stack1", category_gap="60%")
    b.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) \
        .set_global_opts(
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
        # title_opts=opts.TitleOpts(title="处理事件最多的部门"),
        datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], )
    c = (b)

    grid = Grid()

    grid.add(c, grid_opts=opts.GridOpts(pos_bottom="20%"))

    c = grid.dump_options_with_quotes()
    return HttpResponse(c, content_type='application/json')
Ejemplo n.º 10
0
    def html_handle(self, data):
        """
        convert function to html by pyecharts

        Args:
            data(dict): the data info
            
        Returns:
            chart: chart generated by pyecharts: Bar, Pie, Line or Scatter
            filename: html file name
            
        """

        filename = self.table_name + str(data['order']) + '.html'
        margin = str(data['title_top']) + '%'
        # 设置图标基本属性
        if data['chart'] == 'bar':
            chart = (Bar().set_series_opts(label_opts=opts.LabelOpts(
                is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title=data['chartname'],
                                              subtitle=data['describe'],
                                              pos_left='center',
                                              pos_top=margin),
                    xaxis_opts=opts.AxisOpts(name=data['x_name']),
                    yaxis_opts=opts.AxisOpts(
                        name=data['y_name'],
                        splitline_opts=opts.SplitLineOpts(is_show=True))))
        elif data['chart'] == 'pie':
            chart = (Pie().set_global_opts(
                title_opts=opts.TitleOpts(title=data['chartname'],
                                          subtitle=data['describe'],
                                          pos_left='center',
                                          pos_top=margin)))
        elif data['chart'] == 'line':
            chart = (Line().set_series_opts(label_opts=opts.LabelOpts(
                is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title=data['chartname'],
                                              subtitle=data['describe'],
                                              pos_left='center',
                                              pos_top=margin),
                    xaxis_opts=opts.AxisOpts(name=data['x_name']),
                    yaxis_opts=opts.AxisOpts(
                        name=data['y_name'],
                        splitline_opts=opts.SplitLineOpts(is_show=True))))
        elif data['chart'] == 'scatter':
            chart = (Scatter().set_series_opts(label_opts=opts.LabelOpts(
                is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title=data['chartname'],
                                              subtitle=data['describe'],
                                              pos_left='center',
                                              pos_top=margin),
                    xaxis_opts=opts.AxisOpts(
                        type_='value',
                        name=data['x_name'],
                        splitline_opts=opts.SplitLineOpts(is_show=True)),
                    yaxis_opts=opts.AxisOpts(
                        type_='value',
                        name=data['y_name'],
                        splitline_opts=opts.SplitLineOpts(is_show=True))))
        else:
            print("not valid chart")

        if not data["classify"]:  # 在图片上只需展示一组数据
            attr = data["x_data"][0]  # 横坐标
            val = data["y_data"][0]  # 纵坐标
            if data['chart'] == 'bar':
                chart.add_xaxis(attr).add_yaxis(
                    "", val, label_opts=opts.LabelOpts(is_show=False))
            elif data['chart'] == 'line':
                chart.add_xaxis(attr).add_yaxis(
                    "", val, label_opts=opts.LabelOpts(is_show=False))
            elif data['chart'] == 'pie':
                chart.add("", [list(z) for z in zip(attr, val)])
            elif data['chart'] == 'scatter':
                if isinstance(attr[0], str):
                    attr = [x for x in attr if x != '']
                    attr = list(map(float, attr))
                if isinstance(val[0], str):
                    val = [x for x in val if x != '']
                    val = list(map(float, val))
                chart.add_xaxis(attr).add_yaxis(
                    "", val, label_opts=opts.LabelOpts(is_show=False))
        else:  # 在图片上需要展示多组数据
            attr = data["x_data"][0]  # 横坐标
            for i in range(len(data["classify"])):  # 循环输出每组数据
                val = data["y_data"][i]  # 每组纵坐标的值
                name = (data["classify"][i][0] if type(data["classify"][i])
                        == type(('a', 'b')) else data["classify"][i])
                if i == 0:
                    if data['chart'] != 'pie' and data['chart'] != 'scatter':
                        chart.add_xaxis(attr)
                if data['chart'] == 'bar':
                    chart.add_yaxis(name,
                                    val,
                                    stack="stack1",
                                    label_opts=opts.LabelOpts(is_show=False))
                elif data['chart'] == 'line':
                    chart.add_yaxis(name,
                                    val,
                                    label_opts=opts.LabelOpts(is_show=False))
                elif data['chart'] == 'pie':
                    chart.add("", [list(z) for z in zip(attr, val)])
                elif data['chart'] == 'scatter':
                    attr_scatter = data["x_data"][i]
                    if isinstance(attr_scatter[0],
                                  str):  # 去除散点图的空点,并将字符类型转化为数字类型
                        attr_scatter = [x for x in attr_scatter if x != '']
                        attr_scatter = list(map(float, attr_scatter))
                    if isinstance(val[0], str):
                        val = [x for x in val if x != '']
                        val = list(map(float, val))
                    chart.add_xaxis(attr_scatter).add_yaxis(
                        name, val, label_opts=opts.LabelOpts(is_show=False))
        return chart, filename
Ejemplo n.º 11
0
    def show_visualizations(self, number=-1):
        """
        show the charts in jupyter notebook.

        Args:
            number(int): the index of chart to be shown in jupyter notebook.
                         If number == -1, show all the charts in jupyter notebook.
            
        Returns:
            page(Page()): an object of class Page in pyecharts, containing the chart(s)
                          to be shown in jupyter notebook.
            
        """
        instance = self.instance
        if number > instance.view_num:
            print(
                "In function show_visualizations: Error, input number greater than the view numbers."
            )
            return Page()
        if self.rank_method == methods_of_ranking[3]:  # diversified_ranking
            G = myGraph(instance.view_num)
            for i in range(instance.view_num):
                view = instance.tables[instance.views[i].table_pos].views[
                    instance.views[i].view_pos]
                G.addNode(view)
            G.getSim()
            result = G.getTopK(instance.view_num)
        if number != -1:
            begin = number - 1
            end = number
        else:
            begin = 0
            end = instance.view_num
        page = Page()
        for order in range(begin, end):
            if self.rank_method == methods_of_ranking[
                    3]:  # diversified_ranking
                view = G.nodes[result[order]]
            else:
                view = instance.tables[instance.views[order].table_pos].views[
                    instance.views[order].view_pos]
            data = {}
            data['order'] = order
            data['chartname'] = instance.table_name
            data['describe'] = view.table.describe
            data['x_name'] = view.fx.name
            data['y_name'] = view.fy.name
            data['chart'] = Chart.chart[view.chart]
            data['classify'] = [v[0] for v in view.table.classes]
            data['x_data'] = view.X
            data['y_data'] = view.Y
            data['title_top'] = 5

            # 以下代码与html_handle相似
            margin = str(data['title_top']) + '%'

            if data['chart'] == 'bar':
                chart = (Bar().set_series_opts(label_opts=opts.LabelOpts(
                    is_show=False)).set_global_opts(
                        title_opts=opts.TitleOpts(title=data['chartname'],
                                                  subtitle=data['describe'],
                                                  pos_left='center',
                                                  pos_top=margin),
                        xaxis_opts=opts.AxisOpts(name=data['x_name']),
                        yaxis_opts=opts.AxisOpts(
                            name=data['y_name'],
                            splitline_opts=opts.SplitLineOpts(is_show=True))))
            elif data['chart'] == 'pie':
                chart = (Pie().set_global_opts(
                    title_opts=opts.TitleOpts(title=data['chartname'],
                                              subtitle=data['describe'],
                                              pos_left='center',
                                              pos_top=margin)))
            elif data['chart'] == 'line':
                chart = (Line().set_series_opts(label_opts=opts.LabelOpts(
                    is_show=False)).set_global_opts(
                        title_opts=opts.TitleOpts(title=data['chartname'],
                                                  subtitle=data['describe'],
                                                  pos_left='center',
                                                  pos_top=margin),
                        xaxis_opts=opts.AxisOpts(name=data['x_name']),
                        yaxis_opts=opts.AxisOpts(
                            name=data['y_name'],
                            splitline_opts=opts.SplitLineOpts(is_show=True))))
            elif data['chart'] == 'scatter':
                chart = (Scatter().set_series_opts(label_opts=opts.LabelOpts(
                    is_show=False)).set_global_opts(
                        title_opts=opts.TitleOpts(title=data['chartname'],
                                                  subtitle=data['describe'],
                                                  pos_left='center',
                                                  pos_top=margin),
                        xaxis_opts=opts.AxisOpts(
                            type_='value',
                            name=data['x_name'],
                            splitline_opts=opts.SplitLineOpts(is_show=True)),
                        yaxis_opts=opts.AxisOpts(
                            type_='value',
                            name=data['y_name'],
                            splitline_opts=opts.SplitLineOpts(is_show=True))))
            else:
                print("not valid chart")

            if not data["classify"]:
                attr = data["x_data"][0]
                val = data["y_data"][0]
                if data['chart'] == 'bar':
                    chart.add_xaxis(attr).add_yaxis(
                        "", val, label_opts=opts.LabelOpts(is_show=False))
                elif data['chart'] == 'line':
                    chart.add_xaxis(attr).add_yaxis(
                        "", val, label_opts=opts.LabelOpts(is_show=False))
                elif data['chart'] == 'pie':
                    chart.add("", [list(z) for z in zip(attr, val)])
                elif data['chart'] == 'scatter':
                    if isinstance(attr[0], str):
                        attr = [x for x in attr if x != '']
                        attr = list(map(float, attr))
                    if isinstance(val[0], str):
                        val = [x for x in val if x != '']
                        val = list(map(float, val))
                    chart.add_xaxis(attr).add_yaxis(
                        "", val, label_opts=opts.LabelOpts(is_show=False))
                page.add(chart)
            else:
                attr = data["x_data"][0]
                for i in range(len(data["classify"])):
                    val = data["y_data"][i]
                    name = (data["classify"][i][0] if type(data["classify"][i])
                            == type(('a', 'b')) else data["classify"][i])
                    if i == 0:
                        if data['chart'] != 'pie' and data[
                                'chart'] != 'scatter':
                            chart.add_xaxis(attr)
                    if data['chart'] == 'bar':
                        chart.add_yaxis(
                            name,
                            val,
                            stack="stack1",
                            label_opts=opts.LabelOpts(is_show=False))
                    elif data['chart'] == 'line':
                        chart.add_yaxis(
                            name,
                            val,
                            label_opts=opts.LabelOpts(is_show=False))
                    elif data['chart'] == 'pie':
                        chart.add("", [list(z) for z in zip(attr, val)])
                    elif data['chart'] == 'scatter':
                        attr_scatter = data["x_data"][i]
                        if isinstance(attr_scatter[0], str):
                            attr_scatter = [x for x in attr_scatter if x != '']
                            attr_scatter = list(map(float, attr_scatter))
                        if isinstance(val[0], str):
                            val = [x for x in val if x != '']
                            val = list(map(float, val))
                        chart.add_xaxis(attr_scatter).add_yaxis(
                            name,
                            val,
                            label_opts=opts.LabelOpts(is_show=False))
                page.add(chart)
        return page
Ejemplo n.º 12
0
def analyse_data():
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = client['testcomment']
    col = db[collection_name]
    result = col.find({}, {'_id': 0, '评论日期': 1, "评论": 1, "追加评论": 1})
    comment_list = []
    date_list = []
    date_dic = {}
    for date in result:  # 把日期和评论字数放入列表中
        date_list.append(date['评论日期'])
        comment_list.append(len(date['评论']))
        if len(date['追加评论']) != 0:
            comment_list.append(len(date['追加评论']))
    for date in date_list:  # 统计日销量
        if date in date_dic:
            date_dic[date] += 1
        else:
            date_dic[date] = 1
    # date_list = list(date_dic)
    data_dic = {}
    arr = np.array(list(date_dic))  # 给日期排序
    date_list = arr[np.argsort(
        [datetime.strptime(i, '%m.%d') for i in list(date_dic)])].tolist()
    for i in date_list:
        data_dic[i] = date_dic[i]
    # s = pd.Series(data_dic)  # series表示一维数组
    # comment_list.sort()
    word_num_dic = {
        '0-10': 0,
        '11-20': 0,
        '21-30': 0,
        '31-40': 0,
        '41-50': 0,
        '51-60': 0,
        '61-70': 0,
        '71-80': 0,
        '91-100': 0,
        '101-110': 0,
        '111-120': 0,
        '121-130': 0,
        '131-140': 0,
        '141-150': 0,
        '151-160': 0,
        '161-170': 0,
        '171-180': 0,
        '181-190': 0,
        '191-200': 0,
        '201-300': 0
    }
    for i in word_num_dic:  # 统计字数
        for j in comment_list:
            if j >= int(i.split('-')[0]) and j <= int(i.split('-')[-1]):
                word_num_dic[i] += 1
    # print(ndic)
    bar1 = (  # 生成柱状图
        Bar().add_xaxis(list(data_dic.keys())).add_yaxis(
            '商品', list(data_dic.values())).set_global_opts(  # 设置全局参数
                title_opts=opts.TitleOpts(title='商品日销量'),
                yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                    is_show=True)),  # 添加纵坐标标线
                datazoom_opts=[
                    opts.DataZoomOpts(range_start=10,
                                      range_end=80,
                                      is_zoom_lock=False)
                ]  # 添加滑动条
            ))
    bar1.chart_id = '6f180e81787a48539de004c1eb847c1e'
    bar2 = (  # 生成柱状图
        Bar({
            'theme': ThemeType.MACARONS
        }).add_xaxis(list(word_num_dic.keys())).add_yaxis(
            '商品', list(word_num_dic.values())).set_global_opts(  # 设置全局参数
                title_opts=opts.TitleOpts(title='字数统计'),
                yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                    is_show=True)),
                datazoom_opts=[
                    opts.DataZoomOpts(range_start=10,
                                      range_end=80,
                                      is_zoom_lock=False)
                ]))
    bar2.chart_id = '9a412341322b4d92bba49e3fd932a7f0'
    pie1 = (  # 生成柱状图
        Pie().add(series_name='用户身份',
                  data_pair=[('超级会员', vip_num), ('普通用户', comment_num - vip_num)
                             ]).set_global_opts(  # 设置全局参数
                                 title_opts=opts.TitleOpts(title='超级会员比例'), ))
    pie1.chart_id = '7ed5d413532646909f127fd36f584081'
    pie2 = (  # 生成柱状图
        Pie(init_opts=opts.InitOpts(theme=ThemeType.WESTEROS)).add(
            series_name='有无图片',
            data_pair=[('有图评价', img_num), ('无图评价', comment_num - img_num)
                       ]).set_global_opts(  # 设置全局参数
                           title_opts=opts.TitleOpts(title='有图评价比例'), ))
    pie2.chart_id = 'aa3f038854e144dbaa6e9892d4ca31fc'
    pie3 = (  # 生成柱状图
        Pie(init_opts=opts.InitOpts(theme=ThemeType.INFOGRAPHIC)).add(
            series_name='是否追加',
            data_pair=[('追加评价', append_num), ('普通评价', comment_num - append_num)
                       ]).set_global_opts(  # 设置全局参数
                           title_opts=opts.TitleOpts(title='追加评价比例'), ))
    pie3.chart_id = '235863de6fe74a2aa9273e30ed4a7f66'
    page = Page(page_title='评论分析报告')
    page.add(bar1, bar2, pie1, pie2, pie3)
    page.render()
    Page.save_resize_html(cfg_file=r'chart_config.json')
    with open('resize_render.html', 'r+', encoding='utf-8') as f:
        f.seek(573)
        html = f.read()
        f.seek(573)
        f.write('   <h1>评价分析结果:</h1>\n    <p>' + content + '</p>\n ')
        f.write(html)
    print(
        r'已完成分析   请打开E:\Python\learnPython\testspider\FinalProject\resize_render.html查看分析结果'
    )
Ejemplo n.º 13
0
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker

c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
    "商家A", Faker.values()).add_yaxis("商家B", Faker.values()).set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-MarkLine(自定义)")).set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
            markline_opts=opts.MarkLineOpts(
                data=[opts.MarkLineItem(y=50, name="yAxis=50")]),
        ).render("Bar_markline_custom.html"))
Ejemplo n.º 14
0
def draw_charts():
    kline_data = [data[1:-1] for data in chart_data["values"]]
    kline = (Kline().add_xaxis(
        xaxis_data=chart_data["categoryData"]).add_yaxis(
            series_name="Dow-Jones index",
            y_axis=kline_data,
            itemstyle_opts=opts.ItemStyleOpts(color="#ec0000",
                                              color0="#00da3c"),
        ).set_global_opts(
            legend_opts=opts.LegendOpts(is_show=False,
                                        pos_bottom=10,
                                        pos_left="center"),
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=False,
                    type_="inside",
                    xaxis_index=[0, 1],
                    range_start=98,
                    range_end=100,
                ),
                opts.DataZoomOpts(
                    is_show=True,
                    xaxis_index=[0, 1],
                    type_="slider",
                    pos_top="85%",
                    range_start=98,
                    range_end=100,
                ),
            ],
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True,
                    areastyle_opts=opts.AreaStyleOpts(opacity=1)),
            ),
            tooltip_opts=opts.TooltipOpts(
                trigger="axis",
                axis_pointer_type="cross",
                background_color="rgba(245, 245, 245, 0.8)",
                border_width=1,
                border_color="#ccc",
                textstyle_opts=opts.TextStyleOpts(color="#000"),
            ),
            visualmap_opts=opts.VisualMapOpts(
                is_show=False,
                dimension=2,
                series_index=5,
                is_piecewise=True,
                pieces=[
                    {
                        "value": 1,
                        "color": "#00da3c"
                    },
                    {
                        "value": -1,
                        "color": "#ec0000"
                    },
                ],
            ),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True,
                link=[{
                    "xAxisIndex": "all"
                }],
                label=opts.LabelOpts(background_color="#777"),
            ),
            brush_opts=opts.BrushOpts(
                x_axis_index="all",
                brush_link="all",
                out_of_brush={"colorAlpha": 0.1},
                brush_type="lineX",
            ),
        ))

    line = (Line().add_xaxis(xaxis_data=chart_data["categoryData"]).add_yaxis(
        series_name="MA5",
        y_axis=calculate_ma(day_count=5, data=chart_data),
        is_smooth=True,
        is_hover_animation=False,
        linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5),
        label_opts=opts.LabelOpts(is_show=False),
    ).add_yaxis(
        series_name="MA10",
        y_axis=calculate_ma(day_count=10, data=chart_data),
        is_smooth=True,
        is_hover_animation=False,
        linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5),
        label_opts=opts.LabelOpts(is_show=False),
    ).add_yaxis(
        series_name="MA20",
        y_axis=calculate_ma(day_count=20, data=chart_data),
        is_smooth=True,
        is_hover_animation=False,
        linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5),
        label_opts=opts.LabelOpts(is_show=False),
    ).add_yaxis(
        series_name="MA30",
        y_axis=calculate_ma(day_count=30, data=chart_data),
        is_smooth=True,
        is_hover_animation=False,
        linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5),
        label_opts=opts.LabelOpts(is_show=False),
    ).set_global_opts(xaxis_opts=opts.AxisOpts(type_="category")))

    bar = (Bar().add_xaxis(xaxis_data=chart_data["categoryData"]).add_yaxis(
        series_name="Volume",
        y_axis=chart_data["volumes"],
        xaxis_index=1,
        yaxis_index=1,
        label_opts=opts.LabelOpts(is_show=False),
    ).set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            is_scale=True,
            grid_index=1,
            boundary_gap=False,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=False),
            split_number=20,
            min_="dataMin",
            max_="dataMax",
        ),
        yaxis_opts=opts.AxisOpts(
            grid_index=1,
            is_scale=True,
            split_number=2,
            axislabel_opts=opts.LabelOpts(is_show=False),
            axisline_opts=opts.AxisLineOpts(is_show=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    ))

    # Kline And Line
    overlap_kline_line = kline.overlap(line)

    # Grid Overlap + Bar
    grid_chart = Grid(init_opts=opts.InitOpts(
        width="1000px",
        height="800px",
        animation_opts=opts.AnimationOpts(animation=False),
    ))
    grid_chart.add(
        overlap_kline_line,
        grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", height="50%"),
    )
    grid_chart.add(
        bar,
        grid_opts=opts.GridOpts(pos_left="10%",
                                pos_right="8%",
                                pos_top="63%",
                                height="16%"),
    )

    grid_chart.render("professional_kline_brush.html")
Ejemplo n.º 15
0
 def paint_bar(self,
               x: list,
               collects: list,
               title: str,
               mark_point: bool = False):
     bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
     bar.add_xaxis(x)
     for collect in collects:
         for i, (name, unit, data) in enumerate(collect):
             bar.add_yaxis(f'{name}-单位:{unit}', data, yaxis_index=i)
             if i != 0:
                 bar.extend_axis(yaxis=opts.AxisOpts(
                     name='',
                     type_='value',
                     position='right',
                 ))
     bar.set_global_opts(title_opts=opts.TitleOpts(title=title,
                                                   pos_left='5%'),
                         legend_opts=opts.LegendOpts(pos_bottom='0'))
     bar.set_series_opts(
         label_opts=opts.LabelOpts(position='top'),
         tooltip_opts=opts.TooltipOpts(formatter=f'{{b}}年{{a}}:{{c}}'))
     if mark_point:
         bar.set_series_opts(
             markpoint_opts=opts.MarkPointOpts(data=[
                 opts.MarkPointItem(type_='max', name='最大值'),
                 opts.MarkPointItem(type_='min', name='最小值')
             ],
                                               symbol_size=80))
     return bar
Ejemplo n.º 16
0
def get_year_chart(year: int):
    map_data = [
        [[x["name"], x["value"]] for x in d["data"]] for d in data if d["time"] == year
    ][0]
    min_data, max_data = (
        min([d[1][0] for d in map_data]),
        max([d[1][0] for d in map_data]),
    )
    map_chart = (
        Map()
        .add(
            series_name="",
            data_pair=map_data,
            label_opts=opts.LabelOpts(is_show=False),
            is_map_symbol_show=False,
            itemstyle_opts={
                "normal": {"areaColor": "#323c48", "borderColor": "#404a59"},
                "emphasis": {
                    "label": {"show": Timeline},
                    "areaColor": "rgba(255,255,255, 0.5)",
                },
            },
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="1980年以来中国各省GDP排名变化情况",
                subtitle="GDP单位:亿元",
                pos_left="center",
                pos_top="top",
                title_textstyle_opts=opts.TextStyleOpts(
                    font_size=25, color="rgba(255,255,255, 0.9)"
                ),
            ),
            tooltip_opts=opts.TooltipOpts(
                is_show=True,
                formatter=JsCode(
                    """function(params) {
                    if ('value' in params.data) {
                        return params.data.value[2] + ': ' + params.data.value[0];
                    }
                }"""
                ),
            ),
            visualmap_opts=opts.VisualMapOpts(
                is_calculable=True,
                dimension=0,
                pos_left="10",
                pos_top="center",
                range_text=["High", "Low"],
                range_color=["lightskyblue", "yellow", "orangered"],
                textstyle_opts=opts.TextStyleOpts(color="#ddd"),
                min_=min_data,
                max_=max_data,
            ),
        )
    )

    bar_x_data = [x[0] for x in map_data]

    # 这里注释的部分会导致 label 和 value 与 饼图不一致
    # 使用下面的 List[Dict] 就可以解决这个问题了。
    # bar_y_data = [x[1][0] for x in map_data]
    bar_y_data = [{"name": x[0], "value": x[1][0]} for x in map_data]
    bar = (
        Bar()
        .add_xaxis(xaxis_data=bar_x_data)
        .add_yaxis(
            series_name="",
            yaxis_index=1,
            y_axis=bar_y_data,
            label_opts=opts.LabelOpts(
                is_show=True, position="right", formatter="{b}: {c}"
            ),
        )
        .reversal_axis()
        .set_global_opts(
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(is_show=False)),
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(is_show=False)),
            tooltip_opts=opts.TooltipOpts(is_show=False),
            visualmap_opts=opts.VisualMapOpts(
                is_calculable=True,
                dimension=0,
                pos_left="10",
                pos_top="center",
                range_text=["High", "Low"],
                range_color=["lightskyblue", "yellow", "orangered"],
                textstyle_opts=opts.TextStyleOpts(color="#ddd"),
                min_=min_data,
                max_=max_data,
            ),
            graphic_opts=[
                opts.GraphicGroup(
                    graphic_item=opts.GraphicItem(
                        rotation=JsCode("Math.PI / 4"),
                        bounding="raw",
                        right=110,
                        bottom=110,
                        z=100,
                    ),
                    children=[
                        opts.GraphicRect(
                            graphic_item=opts.GraphicItem(left="center", top="center", z=100),
                            graphic_shape_opts=opts.GraphicShapeOpts(width=400, height=50),
                            graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                                fill="rgba(0,0,0,0.3)"
                            ),
                        ),
                        opts.GraphicText(
                            graphic_item=opts.GraphicItem(left="center", top="center", z=100),
                            graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                                text=f"{str(year)} 年",
                                font="bold 26px Microsoft YaHei",
                                graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(fill="#fff"),
                            ),
                        ),
                    ],
                )
            ],
        )
    )

    pie_data = [[x[0], x[1][0]] for x in map_data]
    percent_sum = sum([x[1][1] for x in map_data])
    rest_value = 0
    for d in map_data:
        rest_percent = 100.0
        rest_percent = rest_percent - percent_sum
        rest_value = d[1][0] * (rest_percent / d[1][1])
    pie_data.append(["其他省份", rest_value])
    pie = (
        Pie()
        .add(
            series_name="",
            data_pair=pie_data,
            radius=["12%", "20%"],
            center=["75%", "85%"],
            itemstyle_opts=opts.ItemStyleOpts(
                border_width=1, border_color="rgba(0,0,0,0.3)"
            ),
        )
        .set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{b} {d}%"),
            legend_opts=opts.LegendOpts(is_show=False),
        )
    )

    grid_chart = (
        Grid()
        .add(
            bar,
            grid_opts=opts.GridOpts(
                pos_left="10", pos_right="45%", pos_top="70%", pos_bottom="5"
            ),
        )
        .add(pie, grid_opts=opts.GridOpts())
        .add(map_chart, grid_opts=opts.GridOpts())
    )

    return grid_chart
Ejemplo n.º 17
0
 def paint_bar_stack_with_line(self, x: list, children: dict, parents: dict,
                               sub_title: str):
     for (parent_name, unit), item in children.items():
         bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS))
         bar.add_xaxis(x)
         line = Line()
         line.add_xaxis(x)
         child_names = []
         for child_name, data, overall in item:
             bar.add_yaxis(child_name, data, stack='stack1')
             line.add_yaxis(f'{child_name}占比', overall, yaxis_index=1)
             child_names.append(child_name)
         bar.add_yaxis(parent_name,
                       parents[parent_name],
                       stack='stack1',
                       yaxis_index=0)
         bar.set_global_opts(
             title_opts=opts.TitleOpts(title=','.join(child_names),
                                       subtitle=sub_title,
                                       pos_left='5%'),
             legend_opts=opts.LegendOpts(pos_bottom='0'))
         bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                             tooltip_opts=opts.TooltipOpts(
                                 formatter=f'{{b}}年{{a}}:{{c}}{unit}'),
                             itemstyle_opts=opts.ItemStyleOpts(opacity=0.5))
         bar.extend_axis(yaxis=opts.AxisOpts(
             type_='value',
             name='所占比例',
             min_=0,
             max_=1,
             position='right',
             splitline_opts=opts.SplitLineOpts(
                 is_show=True, linestyle_opts=opts.LineStyleOpts(
                     opacity=1))))
         bar.overlap(line)
         yield bar
from pyecharts import options as opts
from pyecharts.charts import Bar, Line
from pyecharts.faker import Faker

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().add_xaxis(Faker.months).add_yaxis("蒸发量", v1).add_yaxis(
    "降水量", v2).extend_axis(yaxis=opts.AxisOpts(
        axislabel_opts=opts.LabelOpts(
            formatter="{value} °C"), interval=5)).set_series_opts(
                label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title="Overlap-bar+line"),
                    yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
                        formatter="{value} ml")),
                ))

line = Line().add_xaxis(Faker.months).add_yaxis("平均温度", v3, yaxis_index=1)
bar.overlap(line)
bar.render("overlap_bar_line.html")
Ejemplo n.º 19
0
def find_value_render(query_filter, x_label, x, result, Data, query,
                      table_path, answer):

    colorList = ['#f36c6c', '#e6cf4e', '#20d180', '#0093ff']
    # x = ['GDP', 'Industry', 'Architecture', 'Service']
    # y = [990865, 317109, 70904, 534233]
    # x1 = ["周一"]
    # y1 = [11]

    Y = []
    # for i in range(len(y)):
    #     if i==0:
    #         Y.append(
    #             opts.BarItem(
    #                 name=x[i],
    #                 value=round(y[i], 2),
    #                 label_opts=opts.LabelOpts(position="insideTop"),
    #                 itemstyle_opts={
    #                     "normal": {
    #                         "color": colorList[0],
    #                         "barBorderRadius": [30, 30, 30, 30],
    #                     }
    #                 }
    #         ))
    #     else:
    #         Y.append(
    #             opts.BarItem(
    #                 name=x[i],
    #                 value=round(y[i], 2),
    #                 label_opts=opts.LabelOpts(position="insideTop"),
    #                 itemstyle_opts={
    #                     "normal": {
    #                         "color": "blue",
    #                         "barBorderRadius": [30, 30, 30, 30],
    #                     }
    #                 }
    #             ))
    bar1 = Bar()
    bar1.add_xaxis(x)
    bar1.add_yaxis(result[0][0],
                   y_axis=result[0][1],
                   label_opts=opts.LabelOpts(position="insideTop"))
    bar1.set_global_opts(
        yaxis_opts=opts.AxisOpts(is_show=False),
        xaxis_opts=opts.AxisOpts(
            axisline_opts=opts.AxisLineOpts(is_show=False),
            axispointer_opts=opts.AxisPointerOpts(is_show=False),
            axistick_opts=opts.AxisTickOpts(is_show=False)),
        title_opts=opts.TitleOpts(subtitle="When the search condition is " +
                                  query_filter,
                                  pos_left='center'),
        graphic_opts=[
            opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",
                    z=100,
                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=[
                        '\n' + "Q:" + ' ' + query + '\n' + "\n" + 'A:' + ' ' +
                        answer
                    ],
                    font="14px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333")))
        ])
    bar2 = Bar()
    bar2.add_xaxis(x)
    for i in range(len(result)):
        bar2.add_yaxis(result[i][0], y_axis=result[i][1])
    bar2.set_global_opts(
        yaxis_opts=opts.AxisOpts(is_show=False),
        xaxis_opts=opts.AxisOpts(
            axisline_opts=opts.AxisLineOpts(is_show=False),
            axispointer_opts=opts.AxisPointerOpts(is_show=False),
            axistick_opts=opts.AxisTickOpts(is_show=False)),
        graphic_opts=[
            opts.GraphicText(
                graphic_item=opts.GraphicItem(
                    left="center",
                    top="bottom",
                    z=100,
                ),
                graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                    # 可以通过jsCode添加js代码,也可以直接用字符串
                    text=[
                        '\n' + "\n" + "Q:" + ' ' + query + '\n' + "\n" + 'A:' +
                        ' ' + answer
                    ],
                    font="16px Microsoft YaHei",
                    graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                        fill="#333")))
        ])

    Label = []
    data = []
    for i in range(len(Data)):
        Label.append(str(Data[i][0]))
        data.append(Data[i][1])
    data = list(map(list, zip(*data)))
    parallel = Parallel()
    parallel_axis = []
    for i in range(len(Label)):
        parallel_axis.append({"dim": i, "name": Label[i]})
    parallel.add_schema(schema=parallel_axis)
    parallel.add("", data, is_smooth=True)
    parallel.set_global_opts(graphic_opts=[
        opts.GraphicText(
            graphic_item=opts.GraphicItem(
                left="center",
                top="bottom",
                z=100,
            ),
            graphic_textstyle_opts=opts.GraphicTextStyleOpts(
                # 可以通过jsCode添加js代码,也可以直接用字符串
                text=['\n' + "Q:" + ' ' + query + '\n' + 'A:' + ' ' + answer],
                font="14px Microsoft YaHei",
                graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(
                    fill="#333")))
    ])
    grid0 = Grid(init_opts=opts.InitOpts(
        width="100%",
        height="100%",
        renderer=globals.RenderType.SVG,
    ))
    grid0.add(bar1, grid_opts={'left': '20%', 'bottom': '34%'})
    option0 = grid0.dump_options_with_quotes()
    option0 = json.loads(option0)
    grid = Grid(init_opts=opts.InitOpts(
        width="100%",
        height="100%",
        renderer=globals.RenderType.SVG,
    ))
    grid.add(bar2, grid_opts={'left': '15%', 'bottom': '50%'})
    option1 = grid.dump_options_with_quotes()
    option1 = json.loads(option1)
    grid1 = Grid(init_opts=opts.InitOpts(
        width="100%",
        height="100%",
        renderer=globals.RenderType.SVG,
    ))
    grid1.add(parallel, grid_opts={'left': '30%', 'bottom': '34%'})
    option2 = grid1.dump_options_with_quotes()
    option2 = json.loads(option2)

    option = {"option": [option1, option2], "query": query}
    return option
Ejemplo n.º 20
0
 def generate_a_view(data):
     # 设置图标基本属性
     margin = '5%'
     if data['chart'] == 'bar':
         chart = (Bar().set_series_opts(label_opts=opts.LabelOpts(
             is_show=False)).set_global_opts(
                 title_opts=opts.TitleOpts(title=data['chartname'],
                                           subtitle=data['describe'],
                                           pos_left='center',
                                           pos_top=margin),
                 xaxis_opts=opts.AxisOpts(name=data['x_name']),
                 yaxis_opts=opts.AxisOpts(
                     name=data['y_name'],
                     splitline_opts=opts.SplitLineOpts(is_show=True))))
     elif data['chart'] == 'pie':
         chart = (Pie().set_global_opts(
             title_opts=opts.TitleOpts(title=data['chartname'],
                                       subtitle=data['describe'],
                                       pos_left='center',
                                       pos_top=margin)))
     elif data['chart'] == 'line':
         chart = (Line().set_series_opts(label_opts=opts.LabelOpts(
             is_show=False)).set_global_opts(
                 title_opts=opts.TitleOpts(title=data['chartname'],
                                           subtitle=data['describe'],
                                           pos_left='center',
                                           pos_top=margin),
                 xaxis_opts=opts.AxisOpts(name=data['x_name']),
                 yaxis_opts=opts.AxisOpts(
                     name=data['y_name'],
                     splitline_opts=opts.SplitLineOpts(is_show=True))))
     elif data['chart'] == 'scatter':
         chart = (Scatter().set_series_opts(label_opts=opts.LabelOpts(
             is_show=False)).set_global_opts(
                 title_opts=opts.TitleOpts(title=data['chartname'],
                                           subtitle=data['describe'],
                                           pos_left='center',
                                           pos_top=margin),
                 xaxis_opts=opts.AxisOpts(
                     type_='value',
                     name=data['x_name'],
                     splitline_opts=opts.SplitLineOpts(is_show=True)),
                 yaxis_opts=opts.AxisOpts(
                     type_='value',
                     name=data['y_name'],
                     splitline_opts=opts.SplitLineOpts(is_show=True))))
     else:
         print("not valid chart")
     # 添加数据
     attr = data["x_data"]  # 横坐标
     val = data["y_data"]  # 纵坐标
     if data['chart'] == 'bar':
         chart.add_xaxis(attr).add_yaxis(
             "", val, label_opts=opts.LabelOpts(is_show=False))
     elif data['chart'] == 'line':
         chart.add_xaxis(attr).add_yaxis(
             "", val, label_opts=opts.LabelOpts(is_show=False))
     elif data['chart'] == 'pie':
         chart.add("", [list(z) for z in zip(attr, val)])
     elif data['chart'] == 'scatter':
         if isinstance(attr[0], str):
             attr = [x for x in attr if x != '']
             attr = list(map(float, attr))
         if isinstance(val[0], str):
             val = [x for x in val if x != '']
             val = list(map(float, val))
         chart.add_xaxis(attr).add_yaxis(
             "", val, label_opts=opts.LabelOpts(is_show=False))
     return chart
from pywebio.output import put_html
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker

c = (Bar().add_xaxis(
    Faker.choose()).add_yaxis("商家A", Faker.values()).add_yaxis(
        "商家B", Faker.values()).reversal_axis().set_series_opts(
            label_opts=opts.LabelOpts(position="right")).set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-翻转 XY 轴")))

c.width = "100%"
put_html(c.render_notebook())
Ejemplo n.º 22
0
import pandas as pd
import numpy as np
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.options import LabelOpts
from pyecharts.globals import ThemeType

# 读取excel数据
df = pd.read_excel("648(1)(1).xls")
# print(df)

# 获取x数据
time_x = df.iloc[6:, 0].values.tolist()[0:-1:5]
# print(time_x)
# print(len(time_x))

# 获取y轴数据
val_y = df.iloc[6:, 1].values.reshape((5, -1))
avg = np.mean(val_y, axis=0).tolist()
# print(avg)
# # print(val_y)
# print(len(avg))

c = (Bar(init_opts=opts.InitOpts(
    theme=ThemeType.LIGHT)).add_xaxis(time_x).add_yaxis(
        "第一列", avg).set_global_opts(
            title_opts=opts.TitleOpts(title="第一列"),
            datazoom_opts=opts.DataZoomOpts(type_="inside"),
        ).set_series_opts(
            LabelOpts(is_show=False)).render("html/bar_datazoom_inside.html"))
Ejemplo n.º 23
0
def bar_base() -> Bar:
    c = (Bar().add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]).add_yaxis(
        "商家A", [randrange(0, 100) for _ in range(6)]).add_yaxis(
            "商家B", [randrange(0, 100) for _ in range(6)]).set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")))
    return c
Ejemplo n.º 24
0
def test_bar_default_remote_host(fake_writer):
    c = Bar().add_xaxis(["A", "B", "C"]).add_yaxis("series0", [1, 2, 4])
    c.render()
    eq_(c.js_host, "https://assets.pyecharts.org/assets/")
    _, content = fake_writer.call_args[0]
    assert_in("https://assets.pyecharts.org/assets/echarts.min.js", content)
Ejemplo n.º 25
0
def bar_histogram() -> Bar:
    c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
        "商家A", Faker.values(), category_gap=0,
        color=Faker.rand_color()).set_global_opts(title_opts=opts.TitleOpts(
            title="Bar-直方图")))
    return c
Ejemplo n.º 26
0
age_num = sorted(list(age_distribution.index))
age_counts = [int(age_distribution[i]) for i in age_num]

# 年龄分布柱状图
title = 'PYTHON'
subtitle = '年龄分布要求'
age_bar = (
    Bar().add_xaxis(age_num[:-1])  # 剔除“年龄不限”类别
    .add_yaxis('', age_counts[:-1]).set_series_opts(
        label_opts=opts.LabelOpts(is_show=False),
        markpoint_opts=opts.MarkPointOpts(data=[
            opts.MarkPointItem(type_='max', name='最大值'),
            opts.MarkPointItem(type_='min', name='最小值')
        ]),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title=title,
                                  subtitle=subtitle,
                                  pos_left='center'),
        xaxis_opts=opts.AxisOpts(
            name='年龄段',
            position='center',
            axislabel_opts=opts.LabelOpts(formatter="{value}岁")),
        yaxis_opts=opts.AxisOpts(name='职位数', ),
    )
    #     .render(title + '_' + subtitle + '.html')
)

# In[4]:

# 获得各经验段职位数量
experience_dist = df3['experience_required'].value_counts()
Ejemplo n.º 27
0
def bar_different_series_gap() -> Bar:
    c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
        "商家A", Faker.values(),
        gap="0%").add_yaxis("商家B", Faker.values(), gap="0%").set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-不同系列柱间距离")))
    return c
Ejemplo n.º 28
0
from pyecharts.charts import Bar

bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
bar.add_yaxis("商家sfdsdfA", [522, 20, 36, 10, 75, 90])
# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,如 bar.render("mycharts.html")
bar.render()
Ejemplo n.º 29
0
def kline_pro(kline: List[dict],
              fx: List[dict] = None,
              bi: List[dict] = None,
              xd: List[dict] = None,
              bs: List[dict] = None,
              title: str = "缠中说禅K线分析",
              t_seq: List[int] = None,
              width: str = "1400px",
              height: str = '580px') -> Grid:
    """绘制缠中说禅K线分析结果

    :param kline: K线
    :param fx: 分型识别结果
    :param bi: 笔识别结果
        {'dt': Timestamp('2020-11-26 00:00:00'),
          'fx_mark': 'd',
          'start_dt': Timestamp('2020-11-25 00:00:00'),
          'end_dt': Timestamp('2020-11-27 00:00:00'),
          'fx_high': 144.87,
          'fx_low': 138.0,
          'bi': 138.0}
    :param xd: 线段识别结果
    :param bs: 买卖点
    :param title: 图表标题
    :param t_seq: 均线系统
    :param width: 图表宽度
    :param height: 图表高度
    :return: 用Grid组合好的图表
    """
    # 配置项设置
    # ------------------------------------------------------------------------------------------------------------------
    bg_color = "#1f212d"  # 背景
    up_color = "#F9293E"
    down_color = "#00aa3b"

    init_opts = opts.InitOpts(bg_color=bg_color, width=width, height=height, animation_opts=opts.AnimationOpts(False))
    title_opts = opts.TitleOpts(title=title, pos_top="1%",
                                title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20),
                                subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color, font_size=12))

    label_not_show_opts = opts.LabelOpts(is_show=False)
    legend_not_show_opts = opts.LegendOpts(is_show=False)
    red_item_style = opts.ItemStyleOpts(color=up_color)
    green_item_style = opts.ItemStyleOpts(color=down_color)
    k_style_opts = opts.ItemStyleOpts(color=up_color, color0=down_color, border_color=up_color,
                                      border_color0=down_color, opacity=0.8)

    legend_opts = opts.LegendOpts(is_show=True, pos_top="1%", pos_left="30%", item_width=14, item_height=8,
                                  textstyle_opts=opts.TextStyleOpts(font_size=12, color="#0e99e2"))
    brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"],
                                x_axis_index="all", brush_link="all",
                                out_of_brush={"colorAlpha": 0.1}, brush_type="lineX")

    axis_pointer_opts = opts.AxisPointerOpts(is_show=True, link=[{"xAxisIndex": "all"}])

    dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2], range_start=80, range_end=100)
    dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%",
                                  pos_bottom="0%", range_start=80, range_end=100)

    yaxis_opts = opts.AxisOpts(is_scale=True,
                               axislabel_opts=opts.LabelOpts(color="#c7c7c7", font_size=8, position="inside"))

    grid0_xaxis_opts = opts.AxisOpts(type_="category", grid_index=0, axislabel_opts=label_not_show_opts,
                                     split_number=20, min_="dataMin", max_="dataMax",
                                     is_scale=True, boundary_gap=False,
                                     axisline_opts=opts.AxisLineOpts(is_on_zero=False))

    tool_tip_opts = opts.TooltipOpts(
        trigger="axis",
        axis_pointer_type="cross",
        background_color="rgba(245, 245, 245, 0.8)",
        border_width=1,
        border_color="#ccc",
        position=JsCode("""
                    function (pos, params, el, elRect, size) {
    					var obj = {top: 10};
    					obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
    					return obj;
    				}
                    """),
        textstyle_opts=opts.TextStyleOpts(color="#000"),
    )

    # 数据预处理
    # ------------------------------------------------------------------------------------------------------------------
    dts = [x['dt'] for x in kline]
    # k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline]
    k_data = [opts.CandleStickItem(name=i, value=[x['open'], x['close'], x['low'], x['high']])
              for i, x in enumerate(kline)]

    vol = []
    for i, row in enumerate(kline):
        item_style = red_item_style if row['close'] > row['open'] else green_item_style
        bar = opts.BarItem(name=i, value=row['vol'], itemstyle_opts=item_style, label_opts=label_not_show_opts)
        vol.append(bar)

    close = np.array([x['close'] for x in kline], dtype=np.double)
    diff, dea, macd = MACD(close)
    macd_bar = []
    for i, v in enumerate(macd.tolist()):
        item_style = red_item_style if v > 0 else green_item_style
        bar = opts.BarItem(name=i, value=round(v, 4), itemstyle_opts=item_style,
                           label_opts=label_not_show_opts)
        macd_bar.append(bar)

    diff = diff.round(4)
    dea = dea.round(4)

    # K 线主图
    # ------------------------------------------------------------------------------------------------------------------
    chart_k = Kline()
    chart_k.add_xaxis(xaxis_data=dts)
    chart_k.add_yaxis(series_name="Kline", y_axis=k_data, itemstyle_opts=k_style_opts)

    chart_k.set_global_opts(
        legend_opts=legend_opts,
        datazoom_opts=[dz_inside, dz_slider],
        yaxis_opts=yaxis_opts,
        tooltip_opts=tool_tip_opts,
        axispointer_opts=axis_pointer_opts,
        brush_opts=brush_opts,
        title_opts=title_opts,
        xaxis_opts=grid0_xaxis_opts
    )

    # 均线图
    # ------------------------------------------------------------------------------------------------------------------
    chart_ma = Line()
    chart_ma.add_xaxis(xaxis_data=dts)
    if not t_seq:
        t_seq = [10, 20, 60, 120, 250]

    ma_keys = dict()
    for t in t_seq:
        ma_keys[f"MA{t}"] = SMA(close, timeperiod=t)

    for i, (name, ma) in enumerate(ma_keys.items()):
        chart_ma.add_yaxis(series_name=name, y_axis=ma, is_smooth=True,
                           is_selected=True, symbol_size=0, label_opts=label_not_show_opts,
                           linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1))

    chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
    chart_k = chart_k.overlap(chart_ma)

    # 缠论结果
    # ------------------------------------------------------------------------------------------------------------------
    if fx:
        fx_dts = [x['dt'] for x in fx]
        fx_val = [x['fx'] for x in fx]
        chart_fx = Scatter()
        chart_fx.add_xaxis(fx_dts)
        chart_fx.add_yaxis(series_name="FX", y_axis=fx_val, is_selected=False,
                           symbol="circle", symbol_size=6, label_opts=label_not_show_opts,
                           itemstyle_opts=opts.ItemStyleOpts(color="rgba(152, 147, 193, 1.0)", ))

        chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_fx)

    if bi:
        bi_dts = [x['dt'] for x in bi]
        bi_val = [x['bi'] for x in bi]
        chart_bi = Line()
        chart_bi.add_xaxis(bi_dts)
        chart_bi.add_yaxis(series_name="BI", y_axis=bi_val, is_selected=True,
                           symbol="diamond", symbol_size=10, label_opts=label_not_show_opts,
                           itemstyle_opts=opts.ItemStyleOpts(color="rgba(184, 117, 225, 1.0)", ),
                           linestyle_opts=opts.LineStyleOpts(width=1.5))

        chart_bi.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_bi)

    if xd:
        xd_dts = [x['dt'] for x in xd]
        xd_val = [x['xd'] for x in xd]
        chart_xd = Line()
        chart_xd.add_xaxis(xd_dts)
        chart_xd.add_yaxis(series_name="XD", y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10,
                           itemstyle_opts=opts.ItemStyleOpts(color="rgba(37, 141, 54, 1.0)", ))

        chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_xd)

    if bs:
        b_dts = [x['dt'] for x in bs if x['mark'] == 'buy']
        if len(b_dts) > 0:
            b_val = [x['price'] for x in bs if x['mark'] == 'buy']
            chart_b = Scatter()
            chart_b.add_xaxis(b_dts)
            chart_b.add_yaxis(series_name="BUY", y_axis=b_val, is_selected=False, symbol="arrow", symbol_size=8,
                              itemstyle_opts=opts.ItemStyleOpts(color="#f31e1e", ))

            chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_b)

        s_dts = [x['dt'] for x in bs if x['mark'] == 'sell']
        if len(s_dts) > 0:
            s_val = [x['price'] for x in bs if x['mark'] == 'sell']
            chart_s = Scatter()
            chart_s.add_xaxis(s_dts)
            chart_s.add_yaxis(series_name="SELL", y_axis=s_val, is_selected=False, symbol="pin", symbol_size=12,
                              itemstyle_opts=opts.ItemStyleOpts(color="#45b97d", ))

            chart_s.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_s)

    # 成交量图
    # ------------------------------------------------------------------------------------------------------------------
    chart_vol = Bar()
    chart_vol.add_xaxis(dts)
    chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%')
    chart_vol.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            grid_index=1,
            axislabel_opts=opts.LabelOpts(is_show=True, font_size=8, color="#9b9da9"),
        ),
        yaxis_opts=yaxis_opts, legend_opts=legend_not_show_opts,
    )

    # MACD图
    # ------------------------------------------------------------------------------------------------------------------
    chart_macd = Bar()
    chart_macd.add_xaxis(dts)
    chart_macd.add_yaxis(series_name="MACD", y_axis=macd_bar, bar_width='60%')
    chart_macd.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            grid_index=2,
            axislabel_opts=opts.LabelOpts(is_show=False),
        ),
        yaxis_opts=opts.AxisOpts(
            grid_index=2,
            split_number=4,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    )

    line = Line()
    line.add_xaxis(dts)
    line.add_yaxis(series_name="DIFF", y_axis=diff, label_opts=label_not_show_opts, is_symbol_show=False,
                   linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#da6ee8"))
    line.add_yaxis(series_name="DEA", y_axis=dea, label_opts=label_not_show_opts, is_symbol_show=False,
                   linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#39afe6"))

    chart_macd = chart_macd.overlap(line)

    grid0_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="12%", height="58%")
    grid1_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="74%", height="8%")
    grid2_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="86%", height="10%")

    grid_chart = Grid(init_opts)
    grid_chart.add(chart_k, grid_opts=grid0_opts)
    grid_chart.add(chart_vol, grid_opts=grid1_opts)
    grid_chart.add(chart_macd, grid_opts=grid2_opts)
    return grid_chart
Ejemplo n.º 30
0
def draw_chart():
	kline = (
		Kline()
		.add_xaxis(xaxis_data = data["times"])
		.add_yaxis(
			series_name = "",
			y_axis = data["datas"],
			itemstyle_opts = opts.ItemStyleOpts(
				color = "#ef232a",
				color0 = "#14b143",
				border_color = "#ef232a",
				border_color0 = "#14b143"
				),
			markpoint_opts = opts.MarkPointOpts(
				data = [
					opts.MarkPointItem(type_ = "max",name = "最大值"),
					opts.MarkPointItem(type_ = "min",name = "最小值"),
				]
			),
			markline_opts = opts.MarkLineOpts(
				label_opts = opts.LabelOpts(
					position = "middle",
					color = "blue",
					font_size = 15
					),
				data = split_data_part(),
				symbol = ["circle","none"],
				),
			)
		.set_series_opts(
			markarea_opts = opts.MarkAreaOpts(is_silent = True,data = split_data_part())
			)
		.set_global_opts(
			title_opts = opts.TitleOpts(title = "K线周期图表",pos_left = "0"),
			xaxis_opts = opts.AxisOpts(
				type_ = "category",
				is_scale = True,
				boundary_gap = False,
				axisline_opts = opts.AxisLineOpts(is_on_zero = False),
				splitline_opts = opts.SplitLineOpts(is_show = False),
				split_number = 20,
				min_ = "dataMin",
				max_ = "dataMax",
				),
			yaxis_opts = opts.AxisOpts(
				is_scale = True,
				splitline_opts = opts.SplitLineOpts(is_show = True)
				),
			tooltip_opts = opts.TooltipOpts(trigger = "axis",axis_pointer_type = "line"),
			datazoom_opts = [
				opts.DataZoomOpts(
					is_show = True,type_ = "inside",xaxis_index = [0,0],range_end = 100
					),
				opts.DataZoomOpts(
					is_show = True,xaxis_index = [0,1],pos_top = "97%",range_end = 100
					),
				opts.DataZoomOpts(is_show = False,xaxis_index = [0,2],range_end = 100),

			],

			)

		)
	kline_line = (
			Line()
			.add_xaxis(xaxis_data = data["times"])
			.add_yaxis(
				series_name = "MA5",
				y_axis = calculate_ma(day_count = 5),
				is_smooth = True,
				linestyle_opts = opts.LineStyleOpts(opacity = 0.5),
				label_opts = opts.LabelOpts(is_show = False),
				)
			.set_global_opts(
				xaxis_opts = opts.AxisOpts(
					type_ = "category",
					axislabel_opts = opts.LabelOpts(is_show = False),
				),
				yaxis_opts = opts.AxisOpts(
					split_number = 3,
					axisline_opts = opts.AxisLineOpts(is_on_zero = False),
					axistick_opts = opts.AxisTickOpts(is_show = False),
					splitline_opts = opts.SplitLineOpts(is_show = False),
					axislabel_opts = opts.LabelOpts(is_show = True),
					),

				)
		)

	overlap_kline_line = kline.overlap(kline_line)

	bar_1 = (
		Bar()
		.add_xaxis(xaxis_data = data["times"])
		.add_yaxis(
			series_name = "Volumn",
			y_axis = data["vols"],
			label_opts = opts.LabelOpts(is_show = False),
			itemstyle_opts = opts.ItemStyleOpts(
				color = JsCode(
						"""
						function(params){
							var colorList;
							if(barData[params.dataIndex][1] > barData[params.dataIndex][0]){
								colorList = '#ef232a';
							}else{
								colorList = '#14b143';
							}
							return colorList;
						}

						"""
					)
				),
			)
		.set_global_opts(
			xaxis_opts = opts.AxisOpts(
				type_ = "category",
				axislabel_opts = opts.LabelOpts(is_show = False),

				),
			legend_opts = opts.LegendOpts(is_show = False),
			)
		)
	bar_2 = (
		Bar()
		.add_xaxis(xaxis_data = data["times"])
		.add_yaxis(
			series_name = "MACD",
			y_axis = data["macds"],
			label_opts = opts.LabelOpts(is_show = False),
			itemstyle_opts = opts.ItemStyleOpts(
				color = JsCode(
					"""
						function(params){
							var colorList;
							if(params.data >= 0){
								colorList = '#ef232a';
							}else{
								colorList = '#14b143';
							}
							return colorList;
						}
					"""
					)

				),
			)
		.set_global_opts(
			xaxis_opts = opts.AxisOpts(
				type_ = "category",
				axislabel_opts = opts.LabelOpts(is_show = False),
				),
			yaxis_opts = opts.AxisOpts(
				split_number = 4,
				axisline_opts = opts.AxisLineOpts(is_on_zero = False),
				axistick_opts = opts.AxisTickOpts(is_show = False),
				splitline_opts = opts.SplitLineOpts(is_show = False),
				axislabel_opts = opts.LabelOpts(is_show = True),
				),
			legend_opts = opts.LegendOpts(is_show =False),
			)

		)
	line_2 = (
		Line()
		.add_xaxis(xaxis_data = data["times"])
		.add_yaxis(
			series_name = "DIF",
			y_axis = data["difs"],
			label_opts = opts.LabelOpts(is_show =False),
			)
		.set_global_opts(
			legend_opts = opts.LegendOpts(is_show = False)
			)
		)
	overlap_bar_line = bar_2.overlap(line_2)


	grid_chart = Grid(init_opts = opts.InitOpts(width = "1400px",height = "800px",theme = ThemeType.ESSOS))
	grid_chart.add_js_funcs("var barData={}".format(data["datas"]))
	grid_chart.add(
		overlap_kline_line,
		grid_opts = opts.GridOpts(
			pos_left="3%", pos_right="1%", height="60%"
			),
		)

	grid_chart.add(
		bar_1,
		grid_opts = opts.GridOpts(
			pos_left = "3%",pos_right = "1%",pos_top = "71%",height = "10%"
			),
		)


	grid_chart.add(
		overlap_bar_line,
		grid_opts = opts.GridOpts(
			pos_left = "3%",pos_right = "1%",pos_top = "82%",height = "14%"
			)
		)

	grid_chart.render("professional_kline_chart.html")