Beispiel #1
0
def wordcloud_base() -> WordCloud:
    c = (WordCloud().add(
        "", words, word_size_range=[20, 100],
        shape=SymbolType.ARROW).set_global_opts(
            title_opts=opts.TitleOpts(title="A gift for you!"),
            toolbox_opts=opts.ToolboxOpts()))
    return c
Beispiel #2
0
def coincedence(place) -> Bar:
    place = np.array(place)
    foo = place[:, 1].astype(np.float)
    order = np.argsort(foo)
    k = 0
    place1 = np.copy(place)
    for i in order:
        place1[k] = place[i, :]
        k = k + 1
    place = place1
    bar = Bar()
    bar.add_xaxis(list(place[:, 0]))
    bar.add_yaxis("热度", list(place[:, 1]))
    bar.set_global_opts(title_opts=opts.TitleOpts(title="外来旅游人口相关度"))
    bar.set_global_opts(xaxis_opts=opts.AxisOpts(boundary_gap=1,
                                                 interval=0,
                                                 axislabel_opts={"rotate":
                                                                 45}),
                        toolbox_opts=opts.ToolboxOpts(is_show=True),
                        datazoom_opts=[
                            opts.DataZoomOpts(range_start=0,
                                              range_end=100,
                                              is_zoom_lock=False)
                        ])
    #bar.set_global_opts(xaxis_opts=opts.AxisTickOpts(is_align_with_label=0))
    bar.set_series_opts(label_opts=opts.LabelOpts(font_size=9))
    bar.width = 1200
    bar.render(path="外来旅游人口相关度.html")
    return True
Beispiel #3
0
def map_data(data, tableName, titleName) -> Map:
    """
    地图数据生成函数
    :Param data: 地图填充数据
    """
    try:
        name, value = data[0], data[1]
        new_name, new_value = [], []
        for index, temp in enumerate(data[1]):
            if temp > 0:
                new_name.append(name[index])
                new_value.append(value[index])
        name, value = new_name, new_value
        c = (Map(init_opts=opts.InitOpts(page_title="Luwei")).add(
            tableName, [list(z) for z in zip(name, value)],
            "world",
            is_map_symbol_show=False).set_series_opts(
                label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                    title_opts=opts.TitleOpts(title=titleName),
                    visualmap_opts=opts.VisualMapOpts(),
                    toolbox_opts=opts.ToolboxOpts(),
                ))
        return c
    except Exception as ex:
        log.error("Map create failed:{0}".format(str(ex)))
        return None
Beispiel #4
0
def heliu() -> Bar:

    a = [1,10,100,150,180,200]  #模拟确诊
    b = [0,2,20,50,100,102]     #模拟治愈
    c = [0,1,10,15,18,18]   #模拟死亡
    v = list(map(lambda x: x[0]-x[1]-x[2], zip(a, b, c)))   #等待治愈
    x = [0,1,2,3,4,5]   #模拟日  
    c = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))    #设置主题
        
        .add_xaxis(x)   #直接列表
        #.add_yaxis('确诊',v,stack="stack1")
        .add_yaxis('死亡',c,stack="stack3")
        .add_yaxis('治愈',b,stack="stack3")
        .add_yaxis('确诊',v,stack="stack3")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="2019-nCov 海外国家疫情分析", subtitle=""),
            toolbox_opts = opts.ToolboxOpts(is_show = True),  # 
            datazoom_opts=opts.DataZoomOpts(),
            
            )
        .set_series_opts(
                # 设置系列配置
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False),
                singleaxis_opts=opts.SingleAxisOpts(max_=80)
            )            

    )
    return c    
Beispiel #5
0
    def drawline(list1,list4,name):

        # 图表初始化配置
        init_opts = opts.InitOpts(page_title=name)

        line = Line(init_opts=init_opts)
        # 标题配置
        title = opts.TitleOpts(title=name,
                               pos_left="10%")
        # 图例配置
        legend_opts = opts.LegendOpts(orient="horizontal",
                                      pos_top="5%",
                                      pos_right="15%")

        # 工具箱配置
        # feature = opts.ToolBoxFeatureOpts(save_as_image=True, restore=True, data_view=True, data_zoom=True)
        # 工具箱配置
        toolbox_opts = opts.ToolboxOpts(orient="vertical",
                                        pos_bottom="15%",
                                        pos_left="90%",
                                        )

        line.set_global_opts(title_opts=title,
                             legend_opts=legend_opts,
                             toolbox_opts=toolbox_opts,
                             yaxis_opts=opts.AxisOpts(name="单位:岁",
                                                      # axislabel_opts=opts.LabelOpts(formatter="{value}例",
                                                    ),
                             xaxis_opts=opts.AxisOpts(name="日期"),
                            datazoom_opts = opts.DataZoomOpts(orient="vertical"),
                             )
        line.add_xaxis(list4, )
        line.add_yaxis(name, list1, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="#E83132", width="4"))
        line.render('{0}.html'.format(name))
Beispiel #6
0
def bar_base_j() -> Bar:
    j全国 = j['全国'].tolist()
    j农村 = j['农村'].tolist()
    j城镇 = j['城镇'].tolist()
    j东部 = j['东部'].tolist()
    j东北部 = j['东北部'].tolist()
    j中部 = j['中部'].tolist()
    j西部 = j['西部'].tolist()
    JY = j['阶段'].tolist()
    CO = (
        Bar()
            .add_xaxis(JY)
            .add_yaxis("全国", j全国)
            .add_yaxis("农村", j农村)
            .add_yaxis("城镇", j城镇)
            .add_yaxis("东部", j东部)
            .add_yaxis("东北部", j东北部)
            .add_yaxis("中部", j中部)
            .add_yaxis("西部", j西部)
            .set_global_opts(
            title_opts=opts.TitleOpts(title="学科类校外培训参与率", subtitle="全国中小学生(%)"),
            toolbox_opts=opts.ToolboxOpts(),

            datazoom_opts=opts.DataZoomOpts(),
        )
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),

        )

    )
    return CO.render_embed()
Beispiel #7
0
def set_process() -> Bar:
    """
    进程调度比较图
    :return:
    """
    index = ['时间片轮转调度', '短进程优先调度', '非剥夺优先级调度']
    data = [217, 459, 324]
    bar = (
        Bar()
            .add_xaxis(index)
            .add_yaxis(series_name='三大调度算法', yaxis_data=data)
            .set_global_opts(title_opts=opts.TitleOpts(title='三大算法调度性能分析'),
                             xaxis_opts=opts.AxisOpts(type_='category', name='算法名称'),
                             yaxis_opts=opts.AxisOpts(type_='value', name='获胜次数',
                                                      axislabel_opts=opts.LabelOpts(formatter='{value}/次')),
                             toolbox_opts=opts.ToolboxOpts(),
                             tooltip_opts=opts.TooltipOpts(axis_pointer_type='cross')
                             )
            .set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(name='最大值', type_='min'),
                                                                     opts.MarkPointItem(name='最大值', type_='max')]),
                             itemstyle_opts={
                                 "normal": {
                                     "color": JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                             offset: 0,
                                             color: 'rgba(0, 244, 255, 1)'
                                         }, {
                                             offset: 1,
                                             color: 'rgba(0, 77, 167, 1)'
                                         }], false)"""),
                                     "barBorderRadius": [30, 30, 30, 30],
                                     "shadowColor": 'rgb(0, 160, 221)',
                                 }}
                             )
    )
    return bar
Beispiel #8
0
def showAqi():
    # 对空气质量aqi,进行排序
    for row in mycol2.find().sort("name", -1):
        # print("空气质量")
        # print(row)
        # print(row['num'])
        weather_aqis_num.append(row['num'])

    a = []
    b = []
    for i in mycol2.find():
        a.append(i['name'])
        b.append(i['aqi'])
    c = (Bar().add_xaxis(a).add_yaxis("AQI", b).set_global_opts(
        title_opts=opts.TitleOpts(title="空气质量AQI柱状排名图"),
        datazoom_opts=opts.DataZoomOpts(range_start=0, range_end=10),
        toolbox_opts=opts.ToolboxOpts(),
        visualmap_opts=opts.VisualMapOpts(min_=50, max_=100)))
    page.add(c)

    # 展示折线图,空气质量的各种因素

    name = []
    aqi = []
    co = []
    no2 = []
    o3 = []
    pm10 = []
    pm2_5 = []

    so2 = []
    for i in mycol2.find():
        # print(i['name'])
        name.append(i['name'])
        aqi.append(i['aqi'])

        co.append(i['co'])
        no2.append(i['no2'])
        o3.append(i['o3'])
        pm10.append(i['pm10'])
        pm2_5.append(i['pm2_5'])

        so2.append(i['so2'])

    data = []
    for i in range(len(name)):
        t = [aqi[i], co[i], no2[i]]
        data.append(t)
        print(t)

    c = (Line().add_xaxis(name).add_yaxis("aqi(空气质量指数)", aqi).add_yaxis(
        "co", co).add_yaxis("no2", no2).add_yaxis("o3", o3).add_yaxis(
            "pm10",
            pm10).add_yaxis("pm2_5",
                            pm2_5).add_yaxis("so2", so2).set_global_opts(
                                title_opts=opts.TitleOpts(title="空气质量"),
                                datazoom_opts=opts.DataZoomOpts(is_show=True,
                                                                range_start=0,
                                                                range_end=3)))
    page.add(c)
Beispiel #9
0
def hotpoint(movie_name):
    #读取城市数据
    with open(movie_name + '\\' + movie_name + 'dbplaces.txt',
              'r+',
              encoding='utf-8-sig') as f:
        heat_1 = f.read()
        for i in heat_1:
            if i in string.punctuation:
                heat_1 = heat_1.replace(i, "")
        heat = heat_1.split()
        heat_dic = Counter(heat)
    #整理数据
    heat_list = []
    for place, times in heat_dic.items():
        c_word = (place, times)
        heat_list.append(c_word)
    #出图
    heat_map = (Geo().add_schema(maptype="china").add(
        "", heat_list).set_series_opts(label_opts=opts.LabelOpts(
            is_show=False)).set_global_opts(
                visualmap_opts=opts.VisualMapOpts(),
                title_opts=opts.TitleOpts(title=movie_name + " 豆瓣观影热点图",
                                          subtitle=None),
                toolbox_opts=opts.ToolboxOpts(is_show=True)))

    heat_map.render(movie_name + '\\' + movie_name + 'dbhotpoint.html')
Beispiel #10
0
 def post(self, request, *args, **kwargs):
     '''
     导出Echart报表
     '''
     ret = {"code": 1000}
     datas = request.data
     content = json.loads(datas.get("request", ""))
     url_list = []
     duration_list = []
     for i in content:
         url_list.append(i["url"].split("/")[-1])
         duration_list.append(i["duration"])
     print(url_list)
     duration_list = [0 if i == None else i for i in duration_list]
     print(duration_list)
     try:
         # 纵向柱状图
         c = (Bar().add_xaxis(url_list).add_yaxis(
             "Duration", duration_list).set_global_opts(
                 xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
                     rotate=-15)),
                 title_opts=opts.TitleOpts(title="接口响应时长分布图",
                                           subtitle="单位:毫秒(ms)"),
                 toolbox_opts=opts.ToolboxOpts(),
                 legend_opts=opts.LegendOpts(is_show=False),
                 datazoom_opts=opts.DataZoomOpts(),
             ).render("./easy/templates/pyEchartReport.html"))
         ret["msg"] = "生成报表成功"
     except Exception as e:
         print(e)
         ret["code"] = 1001
         ret["error"] = "生成报表异常"
     return Response(ret)
Beispiel #11
0
def plot_one_y(df, title: str):
    df.index = pd.to_datetime(df['date'])
    df.sort_index(inplace=True)
    df = df.drop(['date'], axis=1)
    return (Line(
        init_opts=opts.InitOpts(width="1200px", height="400px")).add_xaxis(
            xaxis_data=df.index.strftime(
                '%Y-%m-%d').values.tolist()).add_yaxis(
                    series_name=title.upper(),
                    y_axis=np.round(df['r2'].values, 2).tolist(),
                    is_smooth=True,
                    label_opts=opts.LabelOpts(is_show=False),
                    linestyle_opts=opts.LineStyleOpts(width=2),
                    markline_opts=opts.MarkLineOpts(
                        data=[opts.MarkLineItem(type_="average")]),
                ).set_global_opts(
                    datazoom_opts=opts.DataZoomOpts(),
                    legend_opts=opts.LegendOpts(pos_bottom="0%",
                                                pos_right='45%'),
                    title_opts=opts.TitleOpts(
                        title=title.upper(),
                        pos_left='0%',
                    ),
                    tooltip_opts=opts.TooltipOpts(trigger="axis",
                                                  axis_pointer_type="cross"),
                    toolbox_opts=opts.ToolboxOpts(is_show=True),
                    xaxis_opts=opts.AxisOpts(boundary_gap=False),
                    yaxis_opts=opts.AxisOpts(
                        axislabel_opts=opts.LabelOpts(formatter="{value}"),
                        splitline_opts=opts.SplitLineOpts(is_show=True),
                    ),
                ).set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[
                    opts.MarkPointItem(type_='max', name='Max'),
                    opts.MarkPointItem(type_='min', name='Min')
                ]), ))
 def print_bar(self):
     bar = Bar(init_opts=opts.InitOpts(width='1080px', height='480px'))
     bar.add_xaxis(self.timedata)
     # category 是同系列直接的距离,gap是不同系列之间的距离
     bar.add_yaxis('治愈人数',
                   self.heal,
                   gap='100%',
                   label_opts=opts.LabelOpts(is_show=False),
                   itemstyle_opts=opts.ItemStyleOpts(color='#90EE90'))
     if self.name == '湖北':
         bar.add_yaxis('死亡人数',
                       self.dead,
                       gap='100%',
                       label_opts=opts.LabelOpts(is_show=False),
                       itemstyle_opts=opts.ItemStyleOpts(color='#696969'))
     # 设置全局变量:x轴标签倾斜度,html主标题
     bar.set_global_opts(datazoom_opts=[
         opts.DataZoomOpts(),
         opts.DataZoomOpts(type_='inside')
     ],
                         toolbox_opts=opts.ToolboxOpts(),
                         xaxis_opts=opts.AxisOpts(name_rotate=-15),
                         title_opts=opts.TitleOpts(self.name,
                                                   subtitle='数据来自inews'))
     line = Line()
     line.add_xaxis(self.timedata)
     line.add_yaxis('确诊人数',
                    self.confirm,
                    label_opts=opts.LabelOpts(is_show=False),
                    itemstyle_opts=opts.ItemStyleOpts(color='#F08080'))
     print(self.name + '.html', '已成功生成到', os.getcwd())
     # 在bar的基础上画line
     bar.overlap(line).render(self.name + '.html')
Beispiel #13
0
def creat_pivot_chart(pivot, index, column, agg, value):
    index_list = pivot.index.tolist()
    column_list = pivot.columns.tolist()
    if pivot.max().tolist():
        visualmap_max = max(pivot.max().tolist())
        range_text = ['最大值', '最小值']
    else:
        visualmap_max = 1
        range_text = ['无', '数据']
    # print(pivot.max())
    data = [(i, j, int(pivot.iloc[i, j])) for i in range(len(index_list))
            for j in range(len(column_list))]
    c = (Bar3D().add(
        series_name=agg + '(' + value + ')',
        data=data,
        shading="lambert",
        xaxis3d_opts=opts.Axis3DOpts(index_list, type_="category", name=index),
        yaxis3d_opts=opts.Axis3DOpts(column_list,
                                     type_="category",
                                     name=column),
        zaxis3d_opts=opts.Axis3DOpts(type_="value",
                                     name=agg + '(' + value + ')'),
    ).set_global_opts(visualmap_opts=opts.VisualMapOpts(max_=visualmap_max,
                                                        range_text=range_text),
                      title_opts=opts.TitleOpts(title="数据透视三维图"),
                      toolbox_opts=opts.ToolboxOpts(),
                      datazoom_opts=opts.DataZoomOpts(type_="inside")))
    return c
Beispiel #14
0
    def line_base(l1, l2) -> Line:

        lh_list = [y["total_box"] for y in l2]
        lh_list.extend([0 for _ in range(3)])  # 前面三天为0

        c = (Line(
            init_opts=opts.InitOpts(bg_color="", page_title="总票房")).add_xaxis(
                [y["date"] for y in reversed(l1)]).add_yaxis(
                    "哪吒之魔童降世", [y["total_box"] for y in reversed(l1)],
                    is_smooth=True,
                    markpoint_opts=opts.MarkPointOpts(
                        data=[opts.MarkPointItem(type_="max")])).add_yaxis(
                            "烈火英雄",
                            reversed(lh_list),
                            is_smooth=True,
                            markpoint_opts=opts.MarkPointOpts(
                                data=[opts.MarkPointItem(
                                    type_="max")])).set_global_opts(
                                        title_opts=opts.TitleOpts(
                                            title="总票房",
                                            subtitle_textstyle_opts={
                                                "color": "red"
                                            },
                                            subtitle="单位: 万元"),
                                        toolbox_opts=opts.ToolboxOpts()))
        return c.render("line.html")
Beispiel #15
0
def redis_qps(request, redis_type, ins_id, redis_ip, redis_port):
    """
    TODO: 目前查看 QPS的趋势图是硬编码,后台只能查看最近60秒的趋势
    :param request:
    :param redis_type:
    :param ins_id:
    :param redis_ip:
    :param redis_port:
    :return:
    """
    real_time_qps = RealTimeQps.objects.all()
    if redis_type == 'sentinel':
        running_ins_time = RunningInsSentinel.objects.all()
    elif redis_type == 'standalone':
        running_ins_time = RunningInsStandalone.objects.all()
    elif redis_type == 'cluster':
        running_ins_time = RunningInsCluster.objects.all()
    real_time_obj = real_time_qps.filter(redis_running_monitor_id=ins_id, redis_ip=redis_ip, redis_port=redis_port).order_by('-collect_date')[:60]
    running_ins = running_ins_time.filter(redis_ip=redis_ip, running_ins_port=redis_port)
    running_ins_name = running_ins.values('running_ins_name').first()
    real_time = [real_time.__dict__['collect_date'] for real_time in real_time_obj]
    redis_qps = [redis_qps.__dict__['redis_qps'] for redis_qps in real_time_obj]
    c = (
        Line()
        .add_xaxis(real_time)
        .add_yaxis(running_ins_name['running_ins_name'], redis_qps, is_smooth=True)
        .set_global_opts(title_opts=opts.TitleOpts(title="{0}:{1}".format(redis_ip,
                                                                          redis_port),
                                                   subtitle="Redis QPS图"),
                         toolbox_opts=opts.ToolboxOpts(),
                         datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],)
    )
    return HttpResponse(c.render_embed())
Beispiel #16
0
def redis_qps(request, ins_id):
    real_time_qps = RealTimeQps.objects.all()
    running_ins_time = RunningInsTime.objects.all()
    real_time_obj = real_time_qps.filter(
        redis_running_monitor_id=ins_id).order_by('-collect_date')[:60]
    running_ins = running_ins_time.filter(id=ins_id)
    running_ins_name = running_ins.values('running_ins_name').first()
    running_ins_ip = running_ins.values('redis_ip').first()
    running_ins_port = running_ins.values('running_ins_port').first()
    real_time = [
        real_time.__dict__['collect_date'] for real_time in real_time_obj
    ]
    redis_qps = [
        redis_qps.__dict__['redis_qps'] for redis_qps in real_time_obj
    ]
    c = (Line().add_xaxis(real_time).add_yaxis(
        running_ins_name['running_ins_name'], redis_qps,
        is_smooth=True).set_global_opts(
            title_opts=opts.TitleOpts(title="{0}:{1}".format(
                running_ins_ip['redis_ip'],
                running_ins_port['running_ins_port']),
                                      subtitle="Redis QPS图"),
            toolbox_opts=opts.ToolboxOpts(),
            datazoom_opts=[
                opts.DataZoomOpts(),
                opts.DataZoomOpts(type_="inside")
            ],
        ))
    return HttpResponse(c.render_embed())
Beispiel #17
0
def bar_base_h() -> Bar:
    学前 = h['学前'].tolist()
    小学 = h['小学'].tolist()
    初中 = h['初中'].tolist()
    普通高中 = h['普通高中'].tolist()
    中职 = h['中职'].tolist()
    HY = h['指标'].tolist()
    CO = (
        Bar()
            .add_xaxis(HY)
            .add_yaxis("学前", 学前)
            .add_yaxis("小学", 小学)
            .add_yaxis("初中", 初中)
            .add_yaxis("普通高中", 普通高中)
            .add_yaxis("中职", 中职)
            .set_global_opts(
            title_opts=opts.TitleOpts(title="2017城农家庭教育支出水平", subtitle="教育支出水平(元)"),
            toolbox_opts=opts.ToolboxOpts(),

            datazoom_opts=opts.DataZoomOpts(),
        )
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),

        )

    )
    return CO.render_embed()
Beispiel #18
0
def bar_datazoom_inside() -> Timeline:
    tl = Timeline()
    for i in range(2014, 2020):
        c = (
            Bar(
            init_opts=opts.InitOpts(
                    animation_opts=opts.AnimationOpts(
                        animation_delay=1000, animation_easing="elasticOut"
                    )
                )
            )
            .add_xaxis(list(zip(list(data总.set_index('类别').index))))
            .add_yaxis("显示",list(data总["{}".format(i)]))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="纵横小说月票榜"),
                datazoom_opts=opts.DataZoomOpts(type_="inside"),
                visualmap_opts=opts.VisualMapOpts(type_="color", max_=250000, min_=200,pos_right='20',pos_top='middle'),
                toolbox_opts=opts.ToolboxOpts(),
            )
            .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="最小值"),
                ]
            ),
        )
    )
        tl.add(c, "{}年".format(i))
    return tl
Beispiel #19
0
def court_pri(keys, values1):
    dict = {}
    for result in results:
        if (result["court"] in keys) and result["court"] not in dict.keys():
            dict[result["court"]] = [result["unit_Price"]]
        elif (result["court"] in keys) and result["court"] in dict.keys():
            dict[result["court"]].append(result["unit_Price"])
    keys1 = list(dict.keys())
    values = list(dict.values())
    list1 = []
    for i in range(len(values)):
        arr_mean = np.mean(values[i])
        list1.append(int(arr_mean))
    # print(values)
    # print(keys)
    # print("长度" + str(len(keys)))
    # print(list1)
    # print("长度" + str(len(list1)))
    b = Bar(init_opts=opts.InitOpts(width="900px", height="900px"))
    b.add_xaxis(keys1)
    b.add_yaxis("小区价格", list1)
    # b.add_yaxis("小区房源",values1)
    b.set_global_opts(title_opts=opts.TitleOpts(title="新乡市",
                                                subtitle="各小区平均价格"),
                      datazoom_opts=opts.DataZoomOpts(),
                      toolbox_opts=opts.ToolboxOpts())
    return b
def draw_map_world(data, to_file, svg_name, label_name, number_max):
    """
    画地图
    :param data:
    :param to_file:
    :param svg_name:
    :param label_name: 图例名称
    :param number_max: 最大值
    :return:
    """
    geo = Map(init_opts=opts.InitOpts(width="800px", height="600px", bg_color='rgb(255, 255, 255)')) \
        .add(label_name, data, maptype="world") \
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                         showLegendSymbol=False) \
        .set_global_opts(legend_opts=opts.LegendOpts(item_width=50,
                                                     item_height=30,
                                                     textstyle_opts=opts.TextStyleOpts(font_size=30)),
                         visualmap_opts=opts.VisualMapOpts(min_=0,
                                                           max_=int(number_max),
                                                           background_color='rgb(255, 255, 255)',
                                                           is_piecewise=True,
                                                           item_width=50,
                                                           item_height=30,
                                                           textstyle_opts=opts.TextStyleOpts(font_size=30)),
                         toolbox_opts=opts.ToolboxOpts(
                             feature=opts.ToolBoxFeatureOpts(
                                 data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False),
                                 # brush=opts.ToolBoxFeatureBrushOpts(is_show=False),
                             )
                         ),
                         )
    # geo.render(to_file)
    make_snapshot(snapshot, geo.render(to_file), svg_name)  # 生成svg图片
Beispiel #21
0
def set_lagou_financing(financing_rank):
    """
    绘制拉勾网企业融资图,采用倒漏斗图
    :param financing_rank:
    :return:漏斗图对象
    """
    # 可以用sorted直接将Counter转化为列表形式,里面嵌套字典
    data = [
        [key, value]
        for key, value in financing_rank.items()
    ]
    funnel = (
        Funnel(init_opts=opts.InitOpts(width='700px', height='500px'))
            .add('企业融资图', data_pair=data, gap=20)
            .set_global_opts(
            title_opts=opts.TitleOpts(title='拉勾网30000+招聘的企业的技术融资情况'),
            toolbox_opts=opts.ToolboxOpts(is_show=False),
            legend_opts=opts.LegendOpts(type_='scroll', orient='vertical',
                                        align='right', legend_icon='circle',
                                        pos_left=1, pos_top=150,
                                        textstyle_opts=opts.TextStyleOpts(font_family='楷体',
                                                                          font_size=16))
        )
    )
    return funnel
 def picture4(self):
     df = pd.read_sql(
         f"select * from {self.table_name} where 检查时间 LIKE '%{self.last_month}%'",
         self.conn)
     group = df.groupby(by=df['责任人岗位']).count()['性质']
     x = group.index.tolist()
     y = group.values.tolist()
     c = (Line(init_opts=opts.InitOpts()).add_xaxis(x).add_yaxis(
         "数量", y).set_global_opts(
             title_opts=opts.TitleOpts(title="现场安全信息责任人岗位统计分布",
                                       subtitle=f"统计时间:{self.last_month}"),
             tooltip_opts=opts.TooltipOpts(trigger="axis"),
             toolbox_opts=opts.ToolboxOpts(is_show=True,
                                           feature={
                                               "saveAsImage": {
                                                   'backgroundColor':
                                                   'white'
                                               },
                                               "dataZoom": {},
                                               "restore": {},
                                               "magicType": {
                                                   "show": True,
                                                   "type": ["line", "bar"]
                                               },
                                               "dataView": {}
                                           }),
             xaxis_opts=opts.AxisOpts(
                 axislabel_opts=opts.LabelOpts(rotate=20), name="责任人岗位")))
     print('已画图成功')
     return c
Beispiel #23
0
    def plot(self):
        self.chart = Bar(init_opts=opts.InitOpts(page_title=self.title))

        # load data
        self.chart.add_xaxis(self.data[0][0])
        index = 0
        for data_set in self.data:
            if len(data_set) > 2:  # get label from data set
                label = data_set[2]
            else:
                label = self.yaxis_name + str(index)
            # self.chart.add_yaxis(label, data_set[1], stack="stack"+str(index))
            self.chart.add_yaxis(label, data_set[1], stack="stack")
            index += 1

        # set options
        self.chart.set_global_opts(
            title_opts=opts.TitleOpts(title=self.title),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            datazoom_opts=opts.DataZoomOpts(is_show=True,
                                            type_='slider',
                                            range_start=0,
                                            range_end=100),
            xaxis_opts=opts.AxisOpts(name=self.xaxis_name,
                                     name_location='end',
                                     name_gap=15),
            yaxis_opts=opts.AxisOpts(
                name=self.yaxis_name,
                name_location='center',
                name_gap=25,
                max_=None if self.count_y <= 1 else int(self.max_sum_y * 1.1)))
        self.chart.set_series_opts(
            label_opts=opts.LabelOpts(is_show=False, position='inside'))

        return self
Beispiel #24
0
def do_charts():
    nvshen = pd.read_csv('nvshen.csv')
    nvshen.sort_values('weight_score', ascending=False, inplace=True)
    bar = Bar()
    count_top = nvshen['count'][0:10].values.tolist()
    count_bottom = nvshen['count'][-10:-1].values.tolist()
    count = [''.join(list(filter(str.isdigit, i))) for i in count_top] + \
            [''.join(list(filter(str.isdigit, i))) for i in count_bottom]
    name_top = nvshen['name'][0:10]
    name_bottom = nvshen['name'][-10:-1]
    name = name_top.values.tolist() + name_bottom.values.tolist()
    score_top = nvshen["weight_score"][0:10]
    score_bottom = nvshen["weight_score"][-10:-1]
    score = score_top.values.tolist() + score_bottom.values.tolist()
    bar.add_xaxis(name)
    bar.add_yaxis("女神得分/百分制", score, gap="0%")
    bar.add_yaxis("打分人数/万", count, gap="0%")
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title="女神大会", subtitle="女神大排名-top10"),
        datazoom_opts=opts.DataZoomOpts(is_show=True, orient="vertical"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-45)),
        toolbox_opts=opts.ToolboxOpts())
    bar.render('女神大排名-top10.html')

    word_name = nvshen['name'].values.tolist()
    word_value = nvshen["weight_score"].values.tolist()
    words = [i for i in zip(word_name, word_value)]
    wordcloud = WordCloud()
    wordcloud.add("", words, word_size_range=[10, 40], shape='circle')
    wordcloud.render("女神词云.html")
def scatter_muti_diemnsion_data():
    c = (
        Scatter()
        .add_xaxis(Faker.choose())
        .add_yaxis(
            "商家A",
            [list(z) for z in zip(Faker.values(), Faker.choose())],
            label_opts=opts.LabelOpts(
                formatter=JsCode(
                    "function (params) {return params.value[1] +' : '+ params.value[2];}"
                )
            ),
        )
        .set_global_opts(
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            tooltip_opts=opts.TooltipOpts(
                formatter=JsCode(
                    "function (params) {return params.name +' : ' +params.value[2];}"
                )
            ),
            visualmap_opts=opts.VisualMapOpts(
                type_="color", max_=150, min_=20, dimension=1
            ),
        )
    )
    return c
Beispiel #26
0
def bar_datazoom_slider(title='Bar-DataZoom(slider-水平)',width="1200px",x_data=['前天','昨天','今天'], \
        y_data = [{'name':'商家A','values':[1,6,7]}],
        toolbox_opts=opts.ToolboxOpts(),
        datazoom_opts=[opts.DataZoomOpts()]
        ) -> Bar:
    '''
    柱状图
    y_data 几根柱子,默认1根
    y_data = [{'name':'商家A','values':[1,6,7]}]

    toolbox_opts 是否展示右上方的小工具,默认展示,不展示传 None
    datazoom_opts 是否展示图表下方可拖动的进度条,默认展示,不展示传 None
    '''
    b = Bar(init_opts=opts.InitOpts(width=width))

    if len(y_data) == 1:
        b.add_yaxis(y_data[0]['name'], y_data[0]['values'])
    if len(y_data) == 2:
        b.add_yaxis(y_data[0]['name'], y_data[0]['values'])
        b.add_yaxis(y_data[1]['name'], y_data[1]['values'])

    b.add_xaxis(x_data)
    b.set_global_opts(
        title_opts=opts.TitleOpts(title=title),
        datazoom_opts=datazoom_opts,
        toolbox_opts=toolbox_opts,
    )
    return b
Beispiel #27
0
def bar_gdp(data):
    """柱状图"""
    try:
        x_data = data[0]
        c = (Bar().add_xaxis(x_data).add_yaxis(
            "增长率(%)",
            list(map(lambda x: round(x, 1), data[1])),
            category_gap="20%",
            color="#675bba").set_global_opts(
                title_opts=opts.TitleOpts(title="人均GDP年增长率"),
                toolbox_opts=opts.ToolboxOpts(),
                yaxis_opts=opts.AxisOpts(offset=0),
                xaxis_opts=opts.AxisOpts(
                    type_="category",
                    offset=int(min(data[1]) * 15),
                    axislabel_opts=opts.LabelOpts(rotate=30,
                                                  font_weight="bold",
                                                  interval=0,
                                                  font_size=12,
                                                  border_width=5),
                ),
            ))
        log.info("柱状图创建成功")
        return c
    except Exception as ex:
        log.error("柱状图创建失败: {0}".format(str(ex)))
        return None
Beispiel #28
0
def line_base():
    c = (
        Line()
        # 传入X轴数据,选择七个品类中的一种中的七样东西
        .add_xaxis(Faker.choose())
        # 传入Y轴数据,第一个参数是系列的名称,第二个参数是数据(随机选择20-150之间的整数)
        # 平滑曲线加上is_smooth=True即可自动平滑
        .add_yaxis('商家A', Faker.values(), is_smooth=True)
        # 隐藏某系列数据False,隐藏后图例是灰色,点击就可以显示出来,默认参数是True显示
        .add_yaxis('商家B', Faker.values(), is_smooth=True, is_selected=True)

        # 设置数据配置项
        # 每个商品的数量是显示在点的上部,改变数据的颜色
        .set_series_opts(label_opts=opts.LabelOpts(
            is_show=True, color='red', position='top'))

        # 设置全局配置项
        .set_global_opts(
            # 显示主副标题
            title_opts=opts.TitleOpts(title='主标题:商家', subtitle='副标题:销售记录'),
            # 显示工具栏,工具栏用于刷新图片,下载图片,查看图片数据等
            toolbox_opts=opts.ToolboxOpts(),
            # 隐藏图例False,默认显示图例True,没有该设置,默认所有图例都显示
            legend_opts=opts.LegendOpts(is_show=True),
            # 设置Y轴坐标刻度
            yaxis_opts=opts.AxisOpts(min_=0, max_=180)))

    # 绘制图片
    pic = c.render()
    return pic
Beispiel #29
0
def musics_rating_bar(id,num) -> Bar:
    (key,val,num) = musics_rating(id,num)
    if key == 0:
        return 0
    c = (
        Bar()
        .add_xaxis([x + '分' for x in key])
        .add_yaxis("音乐数", list(map(str, val)))
        .set_global_opts(title_opts=opts.TitleOpts(title="各评分的音乐数", subtitle="数据量:" + str(num),),
                             yaxis_opts=opts.AxisOpts(name_gap=50,name_rotate=90,name_location="center",name="音乐数(个)"),
                             xaxis_opts=opts.AxisOpts(name="评分"),
                             toolbox_opts=opts.ToolboxOpts(is_show=True,
                                                           #                                         orient="vertical",
                                                           pos_left="95%",
                                                           feature={
                                                               "dataZoom": {"yAxisIndex": "none"},
                                                               "dataView": {},
                                                               "magicType": {
                                                                   "show": True,
                                                                   "title": "切换",
                                                                   "type": ['line', 'bar'],
                                                                   # 启用的动态类型,包括'line'(切换为折线图), 'bar'(切换为柱状图), 'stack'(切换为堆叠模式), 'tiled'(切换为平铺模式)
                                                               },
                                                               "restore": {},
                                                               "saveAsImage": {},
                                                           },
                                                           ),
                            )
        .dump_options_with_quotes()
    )
    return c
Beispiel #30
0
        def get_month_data(search, condition="month"):
            # 获取每个月的数据

            q = Q()
            condition = "date__" + condition
            # print(condition,search)
            q.children.append((condition, search))
            source_info = models.Customer.objects.filter(q).values_list(
                "source").annotate(num=Count("pk"))  # queryset

            # 替换来源称对应的中文名
            source_list = list(
                source_info)  # [('baidu',28)],source_type = (("qq","qq"),)
            source_list = [list(i) for i in source_list]
            for i in range(len(source_list)):
                for j in range(len(models.source_type)):
                    if source_list[i][0] == models.source_type[j][0]:
                        source_list[i][0] = models.source_type[j][1]
            source_list = [tuple(i) for i in source_list]
            # print(source_list)
            pie = (Pie().add(
                "客户来源",
                source_list,
                radius=["30%", "75%"],
                center=["50%", "50%"],
                rosetype="area",
            ).set_global_opts(title_opts=opts.TitleOpts(
                title="2019年客户月流量分析", )).set_series_opts(
                    label_opts=opts.LabelOpts(
                        formatter="{b}: {c}")).set_global_opts(
                            toolbox_opts=opts.ToolboxOpts(orient="vertical")))
            return pie