Beispiel #1
0
def bar_histogram_color() -> Bar:
    x = Faker.dogs + Faker.animal
    xlen = len(x)
    y = []
    for idx, item in enumerate(x):
        if idx <= xlen / 2:
            y.append(
                opts.BarItem(
                    name=item,
                    value=(idx + 1) * 10,
                    itemstyle_opts=opts.ItemStyleOpts(color="#749f83"),
                ))
        else:
            y.append(
                opts.BarItem(
                    name=item,
                    value=(xlen + 1 - idx) * 10,
                    itemstyle_opts=opts.ItemStyleOpts(color="#d48265"),
                ))

    c = (Bar().add_xaxis(x).add_yaxis(
        "series0", y, category_gap=0,
        color=Faker.rand_color()).set_global_opts(title_opts=opts.TitleOpts(
            title="Bar-直方图(颜色区分)")))
    return c
Beispiel #2
0
def tab_fun():
    line = Line().add_xaxis(Faker.choose()).add_yaxis(
        series_name="xx1",
        y_axis=Faker.values(1, 100),
        itemstyle_opts=opts.ItemStyleOpts(color=Faker.rand_color())).add_yaxis(
            series_name="xx2",
            y_axis=Faker.values(1, 100),
            itemstyle_opts=opts.ItemStyleOpts(
                color=Faker.rand_color())).set_global_opts(
                    title_opts=opts.TitleOpts(title="主标题",
                                              subtitle="副标题",
                                              pos_left="10%"),
                    legend_opts=opts.LegendOpts(pos_left="40%"),
                )
    bar = Bar().add_xaxis(Faker.choose()).add_yaxis(
        series_name="柱1",
        y_axis=Faker.values(1, 100),
        itemstyle_opts=opts.ItemStyleOpts(color=Faker.rand_color())).add_yaxis(
            series_name="柱2",
            y_axis=Faker.values(1, 100),
            itemstyle_opts=opts.ItemStyleOpts(
                color=Faker.rand_color())).set_global_opts(
                    title_opts=opts.TitleOpts(title="主标题",
                                              subtitle="副标题",
                                              pos_left="10%"),
                    legend_opts=opts.LegendOpts(pos_left="40%"),
                )

    Tab().add(chart=line, tab_name="选项卡一").add(
        chart=bar, tab_name="选项卡二").render(path="D:/temp/pyecharts_tab.html")
Beispiel #3
0
 def get_dma_chart(xdatas, ddd, ama):
     line = Line()
     line.add_xaxis(xaxis_data=xdatas)
     line.add_yaxis(
         series_name='ddd',
         y_axis=ddd,
         symbol="none",
         is_smooth=True,
         is_hover_animation=False,
         linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9),
         label_opts=opts.LabelOpts(is_show=False),
         itemstyle_opts=opts.ItemStyleOpts(color=Chart.colors[0]),
     )
     line.add_yaxis(
         series_name='ama',
         y_axis=ama,
         symbol="none",
         is_smooth=True,
         is_hover_animation=False,
         linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9),
         label_opts=opts.LabelOpts(is_show=False),
         itemstyle_opts=opts.ItemStyleOpts(color=Chart.colors[1]),
     )
     line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))
     return line
Beispiel #4
0
 def get_turnover_chart(self,df):
     xdatas = df.trade_date.to_numpy().tolist()
     turnovers = df.turnover_rate.to_numpy().tolist()
     volume_ratios = df.volume_ratio.to_numpy().tolist()
     line = Line()
     line.add_xaxis(xaxis_data=xdatas)
     line.add_yaxis(
         series_name='turnover_rate',
         y_axis=turnovers,
         symbol="none",
         is_smooth=True,
         is_hover_animation=False,
         linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9),
         label_opts=opts.LabelOpts(is_show=False),
         itemstyle_opts=opts.ItemStyleOpts(color=Chart.colors[0]),
     )
     line.add_yaxis(
         series_name='volume_ratio',
         y_axis=volume_ratios,
         symbol="none",
         is_smooth=True,
         is_hover_animation=False,
         linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9),
         label_opts=opts.LabelOpts(is_show=False),
         itemstyle_opts=opts.ItemStyleOpts(color=Chart.colors[1]),
     )
     line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))
     return line
Beispiel #5
0
    def get_tanqian(self, tanqian):
        xdatas = tanqian['trade_date'].to_numpy().tolist()
        line = Line()
        line.add_xaxis(xaxis_data=xdatas)

        line.add_yaxis(
            series_name=tanqian['up']['name'],
            y_axis=tanqian['up']['data'].to_numpy().round(2).tolist(),
            symbol="none",
            is_smooth=True,
            is_hover_animation=False,
            linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9),
            label_opts=opts.LabelOpts(is_show=False),
            itemstyle_opts=opts.ItemStyleOpts(color=Chart.colors[20]),
        )
        line.add_yaxis(
            series_name=tanqian['down']["name"],
            y_axis=tanqian['down']['data'].to_numpy().round(2).tolist(),
            symbol="none",
            is_smooth=True,
            is_hover_animation=False,
            linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9),
            label_opts=opts.LabelOpts(is_show=False),
            itemstyle_opts=opts.ItemStyleOpts(color=Chart.colors[22]),
        )
        line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))
        return line
Beispiel #6
0
def bar_custom_bar_color() -> Bar:
    color_function = """
        function (params) {
            if (params.value > 0 && params.value < 50) {
                return 'red';
            } else if (params.value > 50 && params.value < 100) {
                return 'blue';
            }
            return 'green';
        }
        """
    c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
        "商家A",
        Faker.values(),
        itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)),
    ).add_yaxis(
        "商家B",
        Faker.values(),
        itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)),
    ).add_yaxis(
        "商家C",
        Faker.values(),
        itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)),
    ).set_global_opts(title_opts=opts.TitleOpts(title="Bar-自定义柱状颜色")))
    return c
Beispiel #7
0
def draw_tendency(month, day):
    dates = ['1-%d' % i for i in range(16, day + 1)]
    v0 = [4, 17, 59, 78, 92, 149, 131, 259, 444, 688, 769, 1771, 1459, 1576]
    v1 = [4, 17, 59, 77, 72, 105, 69, 105, 180, 323, 371, 1291, 840, 1032]
    c = (Line().add_xaxis(dates).add_yaxis(
        "全国新增确诊病例",
        v0,
        is_smooth=True,
        linestyle_opts=opts.LineStyleOpts(width=4, color='#B44038'),
        itemstyle_opts=opts.ItemStyleOpts(
            color='#B44038', border_color="#B44038",
            border_width=5)).add_yaxis(
                "湖北新增确诊病例",
                v1,
                is_smooth=True,
                linestyle_opts=opts.LineStyleOpts(width=2, color='6FA0A7'),
                label_opts=opts.LabelOpts(position='bottom'),
                itemstyle_opts=opts.ItemStyleOpts(
                    color='#6FA0A7', border_color="#6FA0A7",
                    border_width=3)).set_global_opts(
                        title_opts=opts.TitleOpts(title=""),
                        yaxis_opts=opts.AxisOpts(
                            type_="log",
                            name="y",
                            splitline_opts=opts.SplitLineOpts(is_show=True),
                            is_scale=True,
                            axisline_opts=opts.AxisLineOpts(is_show=False))))
    c.render('charts/%d%d-新增病例趋势图.html' % (month, day))
    return c
Beispiel #8
0
def bar_histogram():
    x = Faker.dogs + Faker.animal
    xlen = len(x)
    y = []
    for idx, item in enumerate(x):
        if idx <= xlen / 2:
            bar_item = opts.BarItem(
                    name=item,
                    value=(idx + 1) * 10,
                    itemstyle_opts=opts.ItemStyleOpts(color="#749f83")
                )
        else:
            bar_item = opts.BarItem(
                    name=item,
                    value=(xlen + 1 - idx) * 10,
                    itemstyle_opts=opts.ItemStyleOpts(color="#d48265"),
                )
        y.append(bar_item)

    obj_bar = Bar()
    obj_bar.add_xaxis(x)
    #直方图就是紧挨着的系列柱category_gap=0调节系列柱之间距离,
    # color=Faker.rand_color()因为上面设置了柱的颜色,这里只对图例legend的颜色起作用
    obj_bar.add_yaxis("series0", y, category_gap=0,color=Faker.rand_color())
    obj_bar.set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-直方图(颜色区分)", subtitle="副标题")
    )
    return obj_bar
Beispiel #9
0
def draw_tendency(month, day):
    dates = ['1-%d' % i for i in range(22, 31 + 1)]
    dates.extend(['2-%02d' % i for i in range(1, day)])
    v0 = [
        131, 259, 444, 688, 769, 1771, 1459, 1737, 1982, 2102, 2590, 2829,
        3235, 3887, 3143, 3399, 2656, 3062, 2478, 2015, 15152, 5090, 2641,
        2009, 2051, 1886, 1749, 385
    ]
    v1 = [
        69, 105, 180, 323, 371, 1291, 840, 1032, 1220, 1347, 1921, 2103, 2345,
        3156, 2447, 2841, 2147, 2618, 2097, 1638, 14840, 4823, 2420, 1843,
        1933, 1807, 1693, 349
    ]
    v2 = [v0[i] - v1[i] for i in range(len(v0))]
    print(v2)
    c = (Line(init_opts=opts.InitOpts(
        width='1000px', height='500px')).add_xaxis(dates).add_yaxis(
            "全国新增确诊病例",
            v0,
            is_smooth=True,
            linestyle_opts=opts.LineStyleOpts(width=4, color='#B44038'),
            itemstyle_opts=opts.ItemStyleOpts(
                color='#B44038', border_color="#B44038",
                border_width=5)).add_yaxis(
                    "湖北新增确诊病例",
                    v1,
                    is_smooth=True,
                    linestyle_opts=opts.LineStyleOpts(width=2,
                                                      color='#4E87ED'),
                    label_opts=opts.LabelOpts(position='bottom'),
                    itemstyle_opts=opts.ItemStyleOpts(
                        color='#4E87ED',
                        border_color="#4E87ED",
                        border_width=3)).add_yaxis(
                            "其他省份新增病例",
                            v2,
                            is_smooth=True,
                            linestyle_opts=opts.LineStyleOpts(width=2,
                                                              color='#F1A846'),
                            label_opts=opts.LabelOpts(position='bottom'),
                            itemstyle_opts=opts.ItemStyleOpts(
                                color='#F1A846',
                                border_color="#F1A846",
                                border_width=3)).set_global_opts(
                                    title_opts=opts.TitleOpts(title=""),
                                    yaxis_opts=opts.AxisOpts(
                                        max_=16000,
                                        min_=10,
                                        type_="log",
                                        name="y",
                                        splitline_opts=opts.SplitLineOpts(
                                            is_show=True),
                                        is_scale=True,
                                        axisline_opts=opts.AxisLineOpts(
                                            is_show=False))))
    root = 'html-charts/%d%d' % (month, day)
    create_dir(root)
    c.render('%s/新增病例趋势图.html' % root)
Beispiel #10
0
    def __draw_zs_area(_ka):
        lines = []
        scatters = []
        for _zs in _ka.zs_list:
            x_start = _zs['start_point']['dt']

            if _zs['zs_finished']:# 中枢完成
                x_end = _zs['end_point']['dt']

                chart_b = EffectScatter()

                if 'buy3' in _zs:
                    chart_b.add_xaxis([_zs['buy3']['dt']])
                    chart_b.add_yaxis(series_name=_ka.freq if aggregation else "B", y_axis=[_zs['buy3']['xd']], is_selected=False, symbol="circle", symbol_size=8,
                                itemstyle_opts=opts.ItemStyleOpts(color="red",))
                    chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
                    scatters.append(chart_b)
                elif 'sell3' in _zs:
                    chart_b.add_xaxis([_zs['sell3']['dt']])
                    chart_b.add_yaxis(series_name=_ka.freq if aggregation else "S", y_axis=[_zs['sell3']['xd']], is_selected=False, symbol="circle", symbol_size=8,
                                itemstyle_opts=opts.ItemStyleOpts(color="green",))
                    chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
                    scatters.append(chart_b)
            elif len(_zs['points'])>=5:# 中枢成立但未完成,有3笔或段以上
                x_end = _zs['points'][-1]['dt']
            else:                       # 中枢未完成,且未确定
                continue
            
            ZD = _zs['ZD']
            ZG = _zs['ZG']
            area_data=[[ {'xAxis': x_start, 'yAxis': ZD, 'value': ZD }, {'xAxis': x_end, 'yAxis': ZG, 'value': ZG }]]
            line = (Line()
            .add_xaxis([x_start, x_end])
            .add_yaxis(series_name=_ka.freq if aggregation else "ZS", y_axis=[ZD, ZG], symbol='none' 
            """        
            , markpoint_opts = opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="ZG"),
                    opts.MarkPointItem(type_="min", name="ZD"),
                ]
            )
            """
            , markline_opts=opts.MarkLineOpts(
                label_opts=opts.LabelOpts(
                    position="middle", color="blue", font_size=15,
                ),
                linestyle_opts=opts.LineStyleOpts(type_="dashed"),
                data=area_data,
                symbol=["none", "none"],
            )
            )
            .set_series_opts(
                markarea_opts=opts.MarkAreaOpts(data=area_data, itemstyle_opts=opts.ItemStyleOpts(color="#dcdcdc",opacity=0.1))
            ))
            lines.append(line)
        return lines, scatters
    def generate_3d_map(self, provinces_data):
        map_3d = Map3D(init_opts=opts.InitOpts(width="1280px", height="720px"))
        map_3d.add_schema(
            itemstyle_opts=opts.ItemStyleOpts(
                color="#172eb2",
                opacity=1,
                border_width=0.8,
                border_color="rgb(76, 96, 255)",
            ),
            map3d_label=opts.Map3DLabelOpts(
                is_show=False,
                formatter=JsCode("function(data){return data.name + "
                                 " + data.value[2];}"),
            ),
            emphasis_label_opts=opts.LabelOpts(
                is_show=False,
                color="#fff",
                font_size=10,
                background_color="rgba(242, 149, 128, 0)",
            ),
            light_opts=opts.Map3DLightOpts(
                main_color="#fff",
                main_intensity=1.2,
                main_shadow_quality="high",
                is_main_shadow=True,
                main_beta=10,
                ambient_intensity=0.3,
            ),
            is_show_ground=True,
            ground_color="#FFF",
        )

        map_3d_data = []
        from .data import provinces_coordinates
        for item in provinces_data.items():
            province_data = (item[0],
                             [*provinces_coordinates[item[0]], item[1]])
            map_3d_data.append(province_data)

        map_3d.add(
            series_name="Data",
            data_pair=map_3d_data,
            type_=ChartType.BAR3D,
            bar_size=1,
            itemstyle_opts=opts.ItemStyleOpts(color="rgb(173, 212, 217)"),
            shading="realistic",
            label_opts=opts.LabelOpts(
                is_show=False,
                formatter=JsCode(
                    "function(data){return data.name + ' ' + data.value[2];}"),
            ),
        )
        map_3d.set_global_opts(title_opts=opts.TitleOpts(title="3D Map"))
        map_3d.render("map3d_with_bar3d.html")
def page_Sankey(nodes_links, title_name):
    # 使用Sankey()函数创建对象赋值给sankey
    # 使用InitOpts(),传入参数theme="dark",bg_color="#253441",赋值给init_opts
    sankey = Sankey(init_opts=opts.InitOpts(theme="dark", bg_color="#253441"))

    # 为创建的实例增加名字(sankey)、传入实验组节点和信息流列表
    sankey.add(
        "sankey",
        nodes=nodes_links[0],
        links=nodes_links[1],
        # 使用LineStyleOpts(),传入参数opacity=0.3, curve=0.5, color="source",赋值给linestyle_opt
        linestyle_opt=opts.LineStyleOpts(opacity=0.3,
                                         curve=0.5,
                                         color="source"),
        # 使用LabelOpts(),传入参数position="right",color="white",font_size=10,赋值给label_opts
        label_opts=opts.LabelOpts(position="right",
                                  color="white",
                                  font_size=10),
        # 使用SankeyLevelsOpts(),传入参数depth为0-5、itemstyle_opts,赋值给列表levels
        levels=[
            opts.SankeyLevelsOpts(
                depth=0,
                # 使用ItemStyleOpts(),传入参数color="#FF8947",border_color="#FF8947"
                itemstyle_opts=opts.ItemStyleOpts(color="#FF8947",
                                                  border_color="#FF8947")),
            opts.SankeyLevelsOpts(
                depth=1,
                # 使用ItemStyleOpts(),传入参数color="#96D15C",border_color="#96D15C"
                itemstyle_opts=opts.ItemStyleOpts(color="#96D15C",
                                                  border_color="#96D15C")),
            opts.SankeyLevelsOpts(
                depth=2,
                # 使用ItemStyleOpts(),传入参数color="#479BED",border_color="#479BED"
                itemstyle_opts=opts.ItemStyleOpts(color="#479BED",
                                                  border_color="#479BED")),
            opts.SankeyLevelsOpts(
                depth=3,
                # 使用ItemStyleOpts(),传入参数color="#55C4CA",border_color="#55C4CA"
                itemstyle_opts=opts.ItemStyleOpts(color="#55C4CA",
                                                  border_color="#55C4CA")),
            opts.SankeyLevelsOpts(
                depth=4,
                # 使用ItemStyleOpts(),传入参数color="#E7BF4F",border_color="#E7BF4F"
                itemstyle_opts=opts.ItemStyleOpts(color="#E7BF4F",
                                                  border_color="#E7BF4F"))
        ])
    # 使用TitleOpts(),传入参数title,赋值给title_opts
    # 使用LegendOpts(),传入参数is_show=False,赋值给legend_opts
    # 调用set_global_opts()
    sankey.set_global_opts(title_opts=opts.TitleOpts(title=title_name),
                           legend_opts=opts.LegendOpts(is_show=False))
    # 使用return返回sankey
    return sankey
 def buy_sell_line(self, tradelist):
     l = Line(init_opts=opts.InitOpts(width=self.width, height=self.height))
     l.set_global_opts(datazoom_opts=opts.DataZoomOpts(type_="inside"))
     x = self.time
     y = [None for i in range(len(x))]
     l.add_xaxis(x)
     l1 = Line(init_opts=opts.InitOpts(width=self.width, height=self.height))
     l2 = Line(init_opts=opts.InitOpts(width=self.width, height=self.height))
     l3 = Line(init_opts=opts.InitOpts(width=self.width, height=self.height))
     l4 = Line(init_opts=opts.InitOpts(width=self.width, height=self.height))
     l1.set_global_opts(datazoom_opts=opts.DataZoomOpts(type_="inside"))
     l2.set_global_opts(datazoom_opts=opts.DataZoomOpts(type_="inside"))
     l3.set_global_opts(datazoom_opts=opts.DataZoomOpts(type_="inside"))
     l4.set_global_opts(datazoom_opts=opts.DataZoomOpts(type_="inside"))
     for d in tradelist:
         # 多头
         if d[6] == 1:
             # 多头盈利
             if d[7] > 0:
                 l1.add_xaxis([d[0], d[3]])
                 l1.add_yaxis("long_win", [d[1], d[4]],
                              is_connect_nones=True,
                              linestyle_opts=opts.LineStyleOpts(color="#FFD700", width=5),
                              itemstyle_opts=opts.ItemStyleOpts(color="#FFD700", opacity=0.6))
             # 多头亏损
             else:
                 l2.add_xaxis([d[0], d[3]])
                 l2.add_yaxis("long_loss", [d[1], d[4]],
                              is_connect_nones=True,
                              linestyle_opts=opts.LineStyleOpts(color="#0088F0", width=3),
                              itemstyle_opts=opts.ItemStyleOpts(color="#0088F0", opacity=0.6))
         # 空头
         elif d[6] == -1:
             # 空头盈利
             if d[7] > 0:
                 l3.add_xaxis([d[0], d[3]])
                 l3.add_yaxis("short_win", [d[1], d[4]],
                              is_connect_nones=True,
                              linestyle_opts=opts.LineStyleOpts(color="#80008f", width=5),
                              itemstyle_opts=opts.ItemStyleOpts(color="#80008f", opacity=0.6))
             # 空头亏损
             else:
                 l4.add_xaxis([d[0], d[3]])
                 l4.add_yaxis("short_loss", [d[1], d[4]],
                              is_connect_nones=True,
                              linestyle_opts=opts.LineStyleOpts(color="#00FA9A", width=3),
                              itemstyle_opts=opts.ItemStyleOpts(color="#00FA9A", opacity=0.6))
     l.overlap(l1)
     l.overlap(l2)
     l.overlap(l3)
     l.overlap(l4)
     return l
Beispiel #14
0
def createDiffKlines(leftDf, rightDf, leftName, rightName):
    kline1_data = [[i[1], i[2], i[3], i[4]] for i in leftDf.to_numpy()]
    kline2_data = [[i[1], i[2], i[3], i[4]] for i in rightDf.to_numpy()]
    kline1 = (
        Kline()
        .add_xaxis(leftDf.iloc[:, 0].tolist())
        .add_yaxis(
            series_name=leftName,
            y_axis=kline1_data,
            yaxis_index=0,
            itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"),
        )
        .extend_axis(yaxis=opts.AxisOpts(position='right'))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="%s -- %s" % (leftName, rightName)),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
            ),
            xaxis_opts=opts.AxisOpts(is_scale=True),
            datazoom_opts=[
                opts.DataZoomOpts(
                    type_="inside",
                    range_start=int((len(leftDf)-60)/len(leftDf)*100),
                    range_end=100,
                ),
                opts.DataZoomOpts(
                    type_="slider",
                    range_start=int((len(leftDf)-60)/len(leftDf)*100),
                    range_end=100,
                ),
            ],
            tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='cross'),
        )
    )

    kline2 = (
        Kline()
        .add_xaxis(rightDf.iloc[:, 0].tolist())
        .add_yaxis(
            series_name=rightName,
            y_axis=kline2_data,
            yaxis_index=1,
            itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"),
        )
    )

    kline1.overlap(kline2)
    return kline1
Beispiel #15
0
def test_map3d_schema(fake_writer):
    c = (Map3D().add_schema(
        itemstyle_opts=opts.ItemStyleOpts(),
        map3d_label=opts.Map3DLabelOpts(),
        light_opts=opts.Map3DLightOpts(),
        view_control_opts=opts.Map3DViewControlOpts(),
        post_effect_opts=opts.Map3DPostEffectOpts(),
        realistic_material_opts=opts.Map3DRealisticMaterialOpts(),
        lambert_material_opts=opts.Map3DLambertMaterialOpts(),
        color_material_opts=opts.Map3DColorMaterialOpts(),
    ).add(
        series_name="商家A",
        data_pair=[list(z) for z in zip(Faker.provinces, Faker.values())],
        maptype="china",
        type_=ChartType.LINES3D,
        effect=opts.Lines3DEffectOpts(),
    ))
    c.render()
    _, content = fake_writer.call_args[0]
    assert_in("itemStyle", content)
    assert_in("label", content)
    assert_in("light", content)
    assert_in("viewControl", content)
    assert_in("postEffect", content)
    assert_in("realisticMaterial", content)
    assert_in("lambertMaterial", content)
    assert_in("colorMaterial", content)
def draw_map():
    """
    绘制世界地图
    遇到一个很神奇的问题:
    两个列表必须写死数据地图才会渲染数据,如果数据是从方法中获得,则地图不渲染数据
    :return:
    """

    # 修复注释中的问题,原因是 confirmed_count 中的 int 是 numpy 的 int ,需转化为 python 中的 int
    # 感谢公众号的 @李康伟 同学提出
    countrys_names, confirmed_count = read_csv()
    confirmed_count_list = []
    for item in confirmed_count:
        confirmed_count_list.append(int(item))

    # countrys_names = ['United States', 'Brazil', 'Russia', 'Spain', 'United Kingdom', 'Italy', 'France', 'Germany', 'Turkey', 'Iran', 'India', 'Peru', 'Canada', 'Saudi Arabia', 'Mexico', 'Chile', 'Belgium', 'Pakistan', 'Netherlands', 'Qatar', 'Ecuador', 'Belarus', 'Sweden', 'Bangladesh', 'Singapore Rep.', 'Switzerland', 'Portugal', 'United Arab Emirates', 'Ireland', 'Indonesia', 'South Africa', 'Poland', 'Ukraine', 'Kuwait', 'Colombia', 'Romania', 'Israel', 'Japan', 'Egypt', 'Austria', 'Dominican Rep.', 'Philippines', 'Denmark', 'Argentina', 'Korea', 'Serbia', 'Panama', 'Afghanistan', 'Czech Rep.', 'Norway', 'Kazakhstan', 'Algeria', 'Nigeria', 'Morocco', 'Oman', 'Malaysia', 'Australia', 'Moldova', 'Ghana', 'Finland', 'Armenia', 'Bolivia', 'Cameroon', 'Iraq', 'Luxembourg', 'Azerbaijan', 'Honduras', 'Hungary', 'Sudan', 'Guinea', 'Uzbekistan', 'Guatemala', 'Thailand', 'Senegal', 'Greece', 'Tajikistan', 'Bulgaria', "Côte d'Ivoire", 'Djibouti', 'Croatia', 'Gabon', 'Cuba', 'Estonia', 'El Salvador', 'Iceland', 'Lithuania', 'Somalia', 'New Zealand', 'Slovakia', 'Slovenia', 'Kyrgyzstan', 'Kenya', 'Guinea Bissau', 'Lebanon', 'Sri Lanka', 'Tunisia', 'Latvia', 'Mali', 'Venezuela', 'Albania', 'Eq. Guinea', 'Niger', 'Cyprus', 'Zambia', 'Costa Rica', 'Haiti', 'Paraguay', 'Burkina Faso', 'Uruguay', 'Georgia', 'Jordan', 'Chad', 'Sierra Leone', 'Nepal', 'Jamaica', 'Tanzania', 'Ethiopia', 'Madagascar', 'Palestine', 'Togo', 'Vietnam', 'Rwanda', 'Montenegro', 'Nicaragua', 'Liberia', 'Swaziland', 'Mauritania', 'Yemen', 'Myanmar', 'Uganda', 'Mozambique', 'Mongolia', 'Brunei', 'Benin', 'Guyana', 'Cambodia', 'The Bahamas', 'Malawi', 'Libya', 'Syria', 'Angola', 'Zimbabwe', 'Burundi', 'Eritrea', 'Botswana', 'Gambia', 'Bhutan', 'East Timor', 'Namibia', 'Lao PDR', 'Fiji', 'Belize', 'Suriname', 'Papua New Guinea', 'Lesotho']
    #
    # confirmed_count = [1666828, 347398, 335882, 281904, 258504, 229327, 182036, 179986, 155686, 133521, 131920, 115754, 85151, 70161, 65856, 65393, 56810, 54601, 45265, 42213, 36258, 35244, 33188, 32078, 31068, 30725, 30471, 28704, 24582, 21745, 21343, 20931, 20580, 20464, 20177, 17857, 16712, 16536, 16513, 16486, 14422, 13777, 11487, 11353, 11190, 11092, 10577, 9998, 8890, 8346, 8322, 8113, 7526, 7406, 7257, 7185, 7114, 6994, 6617, 6568, 6302, 5915, 4400, 4272, 3990, 3982, 3743, 3741, 3628, 3176, 3132, 3054, 3040, 2976, 2876, 2738, 2427, 2366, 2270, 2243, 1934, 1931, 1821, 1819, 1804, 1616, 1594, 1504, 1504, 1468, 1403, 1192, 1114, 1097, 1089, 1048, 1046, 1015, 1010, 989, 960, 943, 927, 920, 918, 865, 850, 814, 764, 728, 704, 648, 621, 584, 550, 509, 494, 488, 423, 373, 325, 325, 324, 279, 255, 238, 227, 212, 201, 198, 168, 141, 141, 135, 127, 124, 100, 82, 75, 70, 61, 56, 42, 39, 30, 25, 24, 24, 20, 19, 18, 18, 11, 8, 2]

    c = (Map().add(
        "确诊人数", [list(z) for z in zip(countrys_names, confirmed_count_list)],
        is_map_symbol_show=False,
        maptype="world",
        label_opts=opts.LabelOpts(is_show=False),
        itemstyle_opts=opts.ItemStyleOpts(
            color="rgb(49,60,72)")).set_series_opts(label_opts=opts.LabelOpts(
                is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title="全球 2019-nCoV 地图"),
                    visualmap_opts=opts.VisualMapOpts(max_=1700000),
                ).render("map_world.html"))
def map3d_china_base() -> Map3D:
    c = (Map3D().add_schema(
        itemstyle_opts=opts.ItemStyleOpts(
            color="rgb(5,101,123)",
            opacity=1,
            border_width=0.8,
            border_color="rgb(62,215,213)",
        ),
        map3d_label=opts.Map3DLabelOpts(
            is_show=True,
            text_style=opts.TextStyleOpts(color="#fff",
                                          font_size=16,
                                          background_color="rgba(0,0,0,0)"),
        ),
        emphasis_label_opts=opts.LabelOpts(is_show=True),
        light_opts=opts.Map3DLightOpts(
            main_color="#fff",
            main_intensity=1.2,
            is_main_shadow=False,
            main_alpha=55,
            main_beta=10,
            ambient_intensity=0.3,
        ),
    ).add(series_name="", data_pair="",
          maptype=ChartType.MAP3D).set_global_opts(
              title_opts=opts.TitleOpts(title="全国行政区划地图-Base"),
              visualmap_opts=opts.VisualMapOpts(is_show=False),
              tooltip_opts=opts.TooltipOpts(is_show=True),
          ))
    return c
Beispiel #18
0
    def get_salary_city(self):
        sql = """
        select city,cast(sum((max_salary+min_salary)/2)/count(*) as signed) salary from lagou_job GROUP BY city order by salary desc
        """
        cursor.execute(sql)
        key = []
        values = []
        for info in cursor.fetchall():
            if not info[0] == '海外':
                key.append(info[0])
                values.append(info[1])

        max = values[0]
        geo = Geo(init_opts=opts.InitOpts(width="1600px", height="1000px"))
        geo.add_schema(
            maptype="china",
            itemstyle_opts=opts.ItemStyleOpts(color="#DDF8FF",
                                              border_color="#111"),
        )
        geo.add("薪资水平", [list(z) for z in zip(key, values)],
                type_="effectScatter")
        geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        geo.set_global_opts(visualmap_opts=opts.VisualMapOpts(max_=max),
                            title_opts=opts.TitleOpts(title="各城市工资水平,单位K"))
        file = data_store + "\\" + "salary.html"
        check_path(file)
        geo.render(file)
Beispiel #19
0
    def process_plot_data(self):
        for s in self.symbol_list:
            # Drop duplicates for x_axis and data
            self.x_axis[s] = pd.DataFrame(self.x_axis[s])
            self.data[s] = pd.DataFrame(self.data[s])
            x_axis_unique = ~self.x_axis[s].duplicated(keep='last')
            self.data[s] = self.data[s][x_axis_unique]
            self.x_axis[s] = self.x_axis[s].drop_duplicates(keep='last')

            # Transform x_axis and data to list
            self.x_axis[s] = self.x_axis[s][0].values.tolist()
            self.data[s] = self.data[s].values.tolist()

            # Transform markpoint to MarkPointItem_list
            markpoint = [
                opts.MarkPointItem(
                    coord=[point[0].strftime('%m-%d %H:%M'), point[1]],
                    value=point[3] + '\n' + str(point[1]),
                    symbol='pin' if point[3] == 'SELL' else 'pin',
                    #symbol_size=30
                    itemstyle_opts=opts.ItemStyleOpts(
                        color='#911146' if point[3] == 'BUY' else '#1F8A70'))
                for point in self.markpoint[s]
            ]

            # Generate markline based on markpoint
            self.markline[s] = [
                opts.MarkLineItem(
                    y=point[1], name='SHORT' if point[3] == 'SELL' else 'LONG')
                for point in self.markpoint[s]
            ]

            self.markpoint[s] = markpoint
Beispiel #20
0
def geo_base() -> Geo:
    c = (Geo().add_schema(
        maptype="china",
        itemstyle_opts=opts.ItemStyleOpts(
            color="#323c48", border_color="#111")).add(
                "人/平方千米", zip(list(df.地区), list(df.人口密度))).set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                        title_opts=opts.TitleOpts(title="2018年36个主要城市的人口密度情况"),
                        visualmap_opts=opts.VisualMapOpts(max_=2306.6,
                                                          min_=18.7,
                                                          is_piecewise=True,
                                                          pieces=[{
                                                              'min':
                                                              924,
                                                              'max':
                                                              2306.593060
                                                          }, {
                                                              'min':
                                                              602,
                                                              'max':
                                                              923.156006
                                                          }, {
                                                              'min':
                                                              362,
                                                              'max':
                                                              600.689035
                                                          }, {
                                                              'min':
                                                              18.781760,
                                                              'max':
                                                              361.142947
                                                          }])))
    return c
Beispiel #21
0
def draw_kline(df_list: List[pd.DataFrame],
               render='html',
               file_name=None) -> Kline:
    kline = None
    for df in df_list:
        security_id = df['security_id'][0]
        security_type, _, _ = decode_security_id(security_id)

        xdata = [to_time_str(timestamp) for timestamp in df.index]

        if security_type == SecurityType.stock:
            ydata = df.loc[:, ['qfq_open', 'qfq_close', 'qfq_low', 'qfq_high'
                               ]].values.tolist()
        else:
            ydata = df.loc[:, ['open', 'close', 'low', 'high']].values.tolist()

        current_kline = get_default_kline()
        current_kline.add_xaxis(xdata)
        current_kline.add_yaxis(security_id,
                                ydata,
                                itemstyle_opts=opts.ItemStyleOpts(
                                    color="#ec0000",
                                    color0="#00da3c",
                                    border_color="#8A0000",
                                    border_color0="#008F28"))

        if not kline:
            kline = current_kline
        else:
            kline.overlap(current_kline)

    if render == 'html':
        kline.render(get_ui_path(file_name))

    return kline
Beispiel #22
0
    def grid_volume(self, grid_index=1):
        """"""
        vol_bar = (Bar().add_xaxis(
            xaxis_data=self.bar_data_datetime).add_yaxis(
                series_name="成交量",
                y_axis=self.bar_data["volume"].tolist(),
                xaxis_index=grid_index,
                yaxis_index=grid_index,
                label_opts=opts.LabelOpts(is_show=False),
                itemstyle_opts=opts.ItemStyleOpts(opacity=0.8,
                                                  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",
                    grid_index=grid_index,
                ),
                legend_opts=opts.LegendOpts(is_show=False),
            ))

        return vol_bar
    def show_dlt(self):
        red_balls = []
        blue_balls = []
        with open(self.input_file, 'r') as f:
            for i in range(Config.PAGES * Config.ITEMS_PER_PAGE):
                one_line_data = f.readline().strip()
                # print(one_line_data)
                red_balls.extend([
                    int(one_line_data[15 + (2 * i):15 + (2 * (i + 1))])
                    for i in range(5)
                ])
                blue_balls.append(int(one_line_data[-4:-2]))
                blue_balls.append(int(one_line_data[-2:]))

        red_counter = Counter(red_balls)
        blue_counter = Counter(blue_balls)
        # print(red_balls)
        # print(blue_balls)
        # print(red_counter)
        # print(blue_counter)
        # print(red_counter.most_common())
        # print(blue_counter.most_common())
        red_dict = {}
        blue_dict = {}
        for i in red_counter.most_common():
            red_dict['{}'.format(i[0])] = i[1]

        for j in blue_counter.most_common():
            blue_dict['{}'.format(j[0])] = j[1]

        print(red_dict)
        print(blue_dict)

        red_list = sorted(red_counter.most_common(),
                          key=lambda number: number[0])
        blue_list = sorted(blue_counter.most_common(),
                           key=lambda number: number[0])
        print(blue_list)
        print(red_list)

        # 红球图表添加
        red_bar = Bar()
        red_x = ['{}'.format(str(x[0])) for x in red_list]
        red_y = ['{}'.format(str(x[1])) for x in red_list]
        red_bar.add_xaxis(red_x)
        red_bar.add_yaxis('红色球出现的次数', red_y)
        # 篮球图表添加
        blue_bar = Bar()
        blue_x = ['{}'.format(str(x[0])) for x in blue_list]
        blue_y = ['{}'.format(str(x[1])) for x in blue_list]
        blue_bar.add_xaxis(blue_x)
        blue_bar.add_yaxis('蓝色球出现的次数',
                           blue_y,
                           itemstyle_opts=opts.ItemStyleOpts(color='blue'))

        page = Page(page_title='大乐透数据分析', interval=3)
        page.add(red_bar)
        page.add(blue_bar)

        page.render(self.output_file)
Beispiel #24
0
def kline_itemstyle() -> Kline:
    c = (
        Kline()
        .add_xaxis(["2017/7/{}".format(i + 1) for i in range(31)])
        .add_yaxis(
            "kline",
            data,
            itemstyle_opts=opts.ItemStyleOpts(
                color="#ec0000",
                color0="#00da3c",
                border_color="#8A0000",
                border_color0="#008F28",
            ),
        )
        .set_global_opts(
            xaxis_opts=opts.AxisOpts(is_scale=True),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
            ),
            datazoom_opts=[opts.DataZoomOpts(type_="inside")],
            title_opts=opts.TitleOpts(title="Kline-ItemStyle"),
        )
    )
    return c
Beispiel #25
0
def charts():
    fp = open('./oldData.txt', 'r')

    # Timeline
    timeline = Timeline(init_opts=opts.InitOpts(
        width="1660px",
        height="708px",
    ))

    # 48 bar charts
    for i in range(48):
        X, Y, Color = getSta(fp)

        # y-axle with color
        y = []
        for j in range(22):
            y.append(
                opts.BarItem(
                    name=X[j],
                    value=Y[j],
                    itemstyle_opts=opts.ItemStyleOpts(color=Color[j])))

        # single bar chart
        bar = (
            Bar().add_xaxis(X).add_yaxis(
                "Youbike 使用率", y).reversal_axis().set_global_opts(
                    title_opts=opts.TitleOpts(
                        title="南港區Youbike的一天",
                        pos_left="center",
                    ),
                    legend_opts=opts.LegendOpts(pos_left="left"),
                    graphic_opts=[
                        opts.GraphicGroup(  # add a block
                            graphic_item=opts.GraphicItem(left="80%",
                                                          top="80%"),
                            children=[
                                opts.GraphicText(  # add text into the block
                                    graphic_item=opts.GraphicItem(
                                        left="center",
                                        top="center",
                                        # z=100
                                    ),
                                    graphic_textstyle_opts=opts.
                                    GraphicTextStyleOpts(
                                        text="{}".format(invTime[i]),
                                        font="48px Verdana",
                                    ),
                                )
                            ])
                    ]).set_series_opts(  # number showed at right of the bar
                        label_opts=opts.LabelOpts(position="right",
                                                  color="#333")))
        timeline.add(bar, "")  # add single bar chart into timeline
        timeline.add_schema(play_interval=1000,
                            is_loop_play=True)  # play settings

    # export into HTML
    timeline.render("YoubikeUsingRate.html")

    fp.close()
Beispiel #26
0
 def bar(self, data, label="", xaxis=None, position=0, show_rgb=False):
     if not xaxis: xaxis = self.xaxis
     rgb_color = {
         "itemstyle_opts": opts.ItemStyleOpts(color=JsCode(
             """
             function(params) {
                 var colorList;
                 if (params.data >= 0) { colorList = '#ef232a'; } else { colorList = '#14b143'; }
                 return colorList;
             }
             """
             )
         )
     }
     if not show_rgb: rgb_color = {}
     return (Bar()
             .add_xaxis(xaxis_data=xaxis)
             .add_yaxis(
                 series_name=label,
                 y_axis=data,
                 label_opts=opts.LabelOpts(is_show=False),
                 **rgb_color
             )
             .set_global_opts(
                 xaxis_opts=opts.AxisOpts(
                     type_="category",
                     grid_index=position,
                     axislabel_opts=opts.LabelOpts(is_show=False),
                 ),
                 legend_opts=opts.LegendOpts(is_show=False),
             )
         )
Beispiel #27
0
 def mapProvince(self, data) -> Map:
     """
     -- 全国各省火车站数量
     :param data:list:[(省份名称,值)]
     :return: Map
     """
     province_map = (
         Map(init_opts=opts.InitOpts(
             width='1000px', height='500px', theme=ThemeType.DARK)).add(
                 '火车站数量', data, "china", zoom=1.2).set_series_opts(
                     label_opts=opts.LabelOpts(is_show=False),  # 关闭各省名称显示
                     itemstyle_opts=opts.ItemStyleOpts(
                         color='rgba(255, 255, 255, 0)'))  # 去掉省会的点
         .set_global_opts(
             visualmap_opts=opts.VisualMapOpts(type_='color',
                                               min_=0,
                                               max_=250),  # 设置最大,最小值
             legend_opts=opts.LegendOpts(is_show=False),  # 不显示图例
             title_opts=opts.TitleOpts(
                 title='全国各省火车站数量分布',
                 title_textstyle_opts=opts.TextStyleOpts(
                     font_size=20),  # 设置标题大小
                 subtitle='全国3500+个车站,数量最多的前三个省是:{},{},{}...  {}'.format(
                     data[0][0], data[1][0], data[2][0],
                     self.data_source))))
     return province_map
def geo_lines_background() -> Geo:
    c = (
        Geo()
        .add_schema(
            maptype="china",
            itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"),
        )
        .add(
            "",
            [("广州", 55), ("北京", 66), ("杭州", 77), ("重庆", 88)],
            type_=ChartType.EFFECT_SCATTER,
            color="white",
        )
        .add(
            "geo",
            [("广州", "上海"), ("广州", "北京"), ("广州", "杭州"), ("广州", "重庆")],
            type_=ChartType.LINES,
            effect_opts=opts.EffectOpts(
                symbol=SymbolType.ARROW, symbol_size=6, color="blue"
            ),
            linestyle_opts=opts.LineStyleOpts(curve=0.2),
        )
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(title_opts=opts.TitleOpts(title="Geo-Lines-background"))
    )
    return c
def line_itemstyle() -> Line:
    c = (
        Line()
        .add_xaxis(xaxis_data=["1990","1991","1992","1993","1994","1995","1996","1997","1998","1999","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016","2017"])
        .add_yaxis(
            "吸烟死亡比例",
            吸烟,
            symbol="triangle",
            symbol_size=20,
            linestyle_opts=opts.LineStyleOpts(color="green", width=4, type_="dashed"),
            label_opts=opts.LabelOpts(is_show=False),
            itemstyle_opts=opts.ItemStyleOpts(
                border_width=3, border_color="yellow", color="blue"
            ),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="中国因吸烟死亡比例"),
            xaxis_opts=opts.AxisOpts(type_="category"),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            tooltip_opts=opts.TooltipOpts(is_show=False),
        )
    )
    return render_template('xyzx.html')
Beispiel #30
0
def kline_base(mydate, data, name) -> Kline:
    kline = (
        Kline()
        .add_xaxis(mydate)
        .add_yaxis("%s" % name, data, markpoint_opts=opts.MarkLineOpts(
            data=[opts.MarkLineItem(type_="max", value_dim="close")]
        ), markline_opts=opts.MarkLineOpts(
            data=[opts.MarkLineItem(type_="max", value_dim="close")]
        ),
                   itemstyle_opts=opts.ItemStyleOpts(
                       color="#ec0000",
                       color0="#00da3c",
                       border_color="#8A0000",
                       border_color0="#008F28",
                   ),
                   )
        .set_global_opts(
            yaxis_opts=opts.AxisOpts(is_scale=True,
                                    splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
            ),
            xaxis_opts=opts.AxisOpts(is_scale=True,
                                    axislabel_opts=opts.LabelOpts(rotate=-30)),
            title_opts=opts.TitleOpts(title="股票走势"),
            datazoom_opts=[opts.DataZoomOpts()],
            toolbox_opts=opts.ToolboxOpts(is_show=True),
        )
    )
    return kline