예제 #1
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")
def bar_datazoom_both() -> Bar:
    a = (Bar().add_xaxis([
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
        "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017",
        "2018"
    ]).add_yaxis("Birth_rate_crude",
                 Birth_rate_crude,
                 color=Faker.rand_color()).add_yaxis(
                     "Primary_completion_rate_total",
                     Primary_completion_rate_total,
                     color=Faker.rand_color()).set_global_opts(
                         title_opts=opts.TitleOpts(title=""),
                         datazoom_opts=[
                             opts.DataZoomOpts(),
                             opts.DataZoomOpts(type_="inside")
                         ],
                     ))
    c = (Bar().add_xaxis([
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
        "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017",
        "2018"
    ]).add_yaxis("GNI_per_capita_Atlas_method",
                 GNI_per_capita_Atlas_method,
                 color=Faker.rand_color()).set_global_opts(
                     title_opts=opts.TitleOpts(title=""),
                     datazoom_opts=[
                         opts.DataZoomOpts(),
                         opts.DataZoomOpts(type_="inside")
                     ],
                 ))
    return render_template("show_pyecharts1.html",
                           bar_data=a.dump_options(),
                           bar_data2=c.dump_options())
예제 #3
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
def bar_histogram_color():
    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
예제 #5
0
def bar_datazoom_inside() -> Bar:
    c = (Bar().add_xaxis(Faker.days_attrs).add_yaxis(
        "商家A", Faker.days_values, color=Faker.rand_color()).set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-DataZoom(inside)"),
            datazoom_opts=opts.DataZoomOpts(type_="inside"),
        ))
    return c
예제 #6
0
def bar_datazoom_slider_vertical() -> Bar:
    c = (Bar().add_xaxis(Faker.days_attrs).add_yaxis(
        "商家A", Faker.days_values, color=Faker.rand_color()).set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-DataZoom(slider-垂直)"),
            datazoom_opts=opts.DataZoomOpts(orient="vertical"),
        ))
    return c
예제 #7
0
def pie_fun():
    Pie().add(
        series_name="饼图名称",
        # 数据格式[[key, value], [key, value], ...], 用 zip 函数将两个 list 进行组合
        data_pair=[list(z) for z in zip(Faker.choose(), Faker.values())],
        # 饼图半径,一个值表示圆半径,两个值表示内外圆半径
        # radius="40%",
        # radius=["40%", "55%"],
        # 中心点的 x、y 位置
        center=["50%", "50%"],
        # 是否展示成南丁格尔图(玫瑰图),通过半径区分数据大小,有 radius 和 area 两种模式
        # radius:扇区圆心角展现数据的百分比,半径展现数据的大小
        # area:所有扇区圆心角相同,仅通过半径展现数据大小
        rosetype="area",
    ).set_series_opts(label_opts=opts.LabelOpts(
        formatter="{b}: {c}",
        color=Faker.rand_color(),
    )).set_global_opts(
        title_opts=opts.TitleOpts(title="主标题",
                                  subtitle="副标题",
                                  pos_left="10%",
                                  pos_top="10%"),
        # 设置 series_name 位置
        legend_opts=opts.LegendOpts(pos_left="30%", pos_top="10%"),
    ).render(
        # 设置输出路径
        path="D:/temp/pyecharts_pie.html")
예제 #8
0
def draw_bar_plays(data,user_id,title="听歌方式"):
    """
    两种听歌方式
    :param plays:
    :param user_id:
    :param title:
    :return:
    """
    file_name = "user_data/" + str(user_id) + "_bar_plays.html"
    x = ["片段播放", "完整播放"]
    color = ["#749f83", "#d48265"]

    xlen = len(x)
    y = []
    for idx, item in enumerate(x):

        y.append(
            opts.BarItem(
                name=item,
                value=data[idx],
                itemstyle_opts=opts.ItemStyleOpts(color=color[idx]),
            )
        )
    c = (
        Bar()
            .add_xaxis(x)
            .add_yaxis("用户:"+str(user_id), y,color=Faker.rand_color())
            .set_global_opts(title_opts=opts.TitleOpts(title=title),toolbox_opts=opts.ToolboxOpts())
            #.render(file_name)
    )
    return c
예제 #9
0
def draw_bar_recoder(data,user_id,title = "用户行为统计"):
    """
    用户行为统计
    :param data:
    :param user_id:
    :param title:
    :return:
    """
    file_name = "user_data/" + str(user_id) + "_bar_recoder.html"
    x = ["循环播放","片段播放","查看评论","点赞评论","收藏歌曲"]
    color = ["#F79709","#749f83", "#d48265","#33CCCC","#82C182"]
    xlen = len(x)
    y = []
    for idx, item in enumerate(x):
        y.append(
            opts.BarItem(
                name=item,
                value=data[idx][1],
                itemstyle_opts=opts.ItemStyleOpts(color=color[idx]),
            )
        )
    c = (
        Bar()
            .add_xaxis(x)
            .add_yaxis("" , y, color=Faker.rand_color())
            .set_global_opts(title_opts=opts.TitleOpts(title=title),
                             toolbox_opts=opts.ToolboxOpts()
                             )
            # .render(file_name)
    )
    return c
예제 #10
0
def draw_bar_like(data,user_id,title="偏爱曲风统计"):
    """
    柱状图 偏爱统计
    :param data:
    :param user_id:
    :param title:
    :return:
    """
    file_name = "user_data/" + str(user_id) + "_bar_like.html"
    x = ["古风", "古典", "电子", "民谣", "流行", "说唱", "摇滚"]
    color = ["#C43C3C", "#7D573E", "#E6E65D", "#69DA69", "#70D4D4", "#9B7CC7", "#A2A2A2"]
    xlen = len(x)
    y = []
    for idx, item in enumerate(x):
        y.append(
            opts.BarItem(
                name=item,
                value=data[idx][1],
                itemstyle_opts=opts.ItemStyleOpts(color=color[idx]),
            )
        )
    c = (
        Bar()
            .add_xaxis(x)
            .add_yaxis("", y, color=Faker.rand_color())
            .set_global_opts(title_opts=opts.TitleOpts(title=title),
                             toolbox_opts=opts.ToolboxOpts()
                             )
            #.render(file_name)
    )
    return c
예제 #11
0
def action_type_bar3(session, min, max):
    print(min)
    print(max)
    min = float(int(min))/100
    max = float(int(max))/100
    if not session['is_login']:
        return None
    user_id = session['user_id']
    sql = "select discount,ROI from t_roi where discount >={} and discount < {} and merchant_id = {}".format(min, max, user_id)
    cursor.execute(sql)
    res = cursor.fetchall()
    xs = list(map(lambda x: str(x[0]), res))
    ys = list(map(lambda x: (x[1]), res))
    print("xs:{}".format(xs))
    print(type(ys[0]))
    print("ys:{}".format(ys))
    line = (
        Line().add_xaxis(xs).add_yaxis("roi曲线", ys, is_smooth=True,
                                       areastyle_opts=opts.AreaStyleOpts(opacity=0.5,
                                                                         color=Faker.rand_color()))
            .set_global_opts(
            title_opts=opts.TitleOpts(title=""),
            yaxis_opts=opts.AxisOpts(name="roi曲线图"),
            xaxis_opts=opts.AxisOpts(
                name="折扣",
                axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                is_scale=False,
                boundary_gap=False,
            ),

        ).dump_options_with_quotes()
    )

    return [json.loads(line)]
예제 #12
0
def render_vertical_datazoom_py():
    with st.echo("below"):
        c = (Bar().add_xaxis(Faker.days_attrs).add_yaxis(
            "商家A", Faker.days_values,
            color=Faker.rand_color()).set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-DataZoom(slider-垂直)"),
                datazoom_opts=opts.DataZoomOpts(orient="vertical"),
            ))
        st_pyecharts(c, height="400px")
예제 #13
0
def bar_histogram():
    obj_bar = Bar()
    obj_bar.add_xaxis(Faker.choose())
    #直方图就是紧挨着的系列柱category_gap=0调节系列柱之间距离,color=Faker.rand_color()随机颜色
    obj_bar.add_yaxis("商家A", Faker.values(),category_gap=0, color=Faker.rand_color())
    obj_bar.set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-直方图", subtitle="副标题")
    )
    return obj_bar
예제 #14
0
파일: app.py 프로젝트: bakasui/python_final
def bar_sea_place() -> Bar:
    c = (
        Bar()
        .add_xaxis(sea_ename)
        .add_yaxis("东南亚",place_sum, color=Faker.rand_color())
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Bar-东南亚各国景观/目的地数"),
            datazoom_opts=[opts.DataZoomOpts()],  
        )
        )
    return c.render_embed()
예제 #15
0
def timeline(list, title, name):
    attr = Faker.choose()
    tl = Timeline()
    for i in list:
        x_list = ['每日死亡', '累计死亡', '每日确诊', '累计确诊']
        y_list = []
        for x in range(5, 9):
            y_list.append(i[x])
        histogram = (Bar().add_xaxis(x_list).add_yaxis(
            name, y_list, color=Faker.rand_color()))
        tl.add(histogram, "{}年".format(transform_time(i[0])))
    return tl
예제 #16
0
파일: app.py 프로젝트: bakasui/python_final
 def bar_each_place() -> Bar:
     c = (
         Bar()
         .add_xaxis(each_country_city_name)
         .add_yaxis(str(country),each_country_city_place,color=Faker.rand_color())
         .set_global_opts(
             title_opts=opts.TitleOpts(title="Bar-"+str(country)+"各地景观/目的地数"),
             datazoom_opts=[opts.DataZoomOpts()],  
         )
         
     )
     return c.render_embed()
예제 #17
0
def line_fun():
    Line().add_xaxis(
        # 添加 x 轴数据
        Faker.choose()).add_yaxis(
            # 添加 y 轴数据,并设置属性
            series_name="xx1",
            y_axis=Faker.values(1, 100),
            itemstyle_opts=opts.ItemStyleOpts(
                color=Faker.rand_color())).add_yaxis(
                    # 添加 y 轴数据,并设置属性
                    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%"),
                            # 设置 series_name 位置
                            legend_opts=opts.LegendOpts(pos_left="40%"),
                        ).render(
                            # 设置输出路径
                            path="D:/temp/pyecharts_line.html")
예제 #18
0
def CumulativeConfirmed_histogram(list, title, name):
    x_list = []
    y_list = []
    for i in list:
        x_list.append(transform_time(i[0]))
        y_list.append(i[8])
    histogram = (Bar().add_xaxis(x_list).add_yaxis(
        '累计确诊', y_list,
        color=Faker.rand_color()).set_global_opts(datazoom_opts=[
            opts.DataZoomOpts(),
            opts.DataZoomOpts(type_="inside")
        ], ).set_series_opts(label_opts=opts.LabelOpts(is_show=False)))
    return histogram
예제 #19
0
def map_fun():
    Map().add(
        series_name="全国疫情数据",
        data_pair=[list(z) for z in zip(Faker.provinces, Faker.values())],
        maptype="china").set_series_opts(label_opts=opts.LabelOpts(
            #formatter="{b}: {c}",
            color=Faker.rand_color(), )).set_global_opts(
                title_opts=opts.TitleOpts(title="主标题",
                                          subtitle="副标题",
                                          pos_left="10%",
                                          pos_top="10%"),
                # 设置 series_name 位置
                legend_opts=opts.LegendOpts(pos_left="30%", pos_top="10%"),
                # Map 视觉效果
                visualmap_opts=opts.VisualMapOpts(),
            ).render(
                # 设置输出路径
                path="D:/temp/pyecharts_map.html")
    Geo().add_schema(maptype="china").add(
        series_name="全国疫情数据",
        data_pair=[list(z) for z in zip(Faker.provinces, Faker.values())],
    ).set_series_opts(label_opts=opts.LabelOpts(
        formatter="{b}: {c}",
        color=Faker.rand_color(),
    )).set_global_opts(
        title_opts=opts.TitleOpts(title="主标题",
                                  subtitle="副标题",
                                  pos_left="10%",
                                  pos_top="10%"),
        # 设置 series_name 位置
        # legend_opts=opts.LegendOpts(pos_left="30%", pos_top="10%"),
        # Geo 视觉效果
        visualmap_opts=opts.VisualMapOpts(),
    ).render(
        # 设置输出路径
        path="D:/temp/pyecharts_geo.html")
예제 #20
0
def show_bar(id):
    fix_data()
    bar = Bar(init_opts=opts.InitOpts(
        width='1200px', height='800px', page_title='page'))
    bar.add_xaxis(fix_id)
    bar.add_yaxis('线程', fix_time, stack="stack1", color=Faker.rand_color())
    bar.reversal_axis()
    bar.set_global_opts(title_opts=opts.TitleOpts(title="压测时间图"),
                        datazoom_opts=opts.DataZoomOpts(orient="vertical"))
    bar.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="最小值"),
                            opts.MarkPointItem(type_="average", name="平均值"),
                        ]))
    bar.render('压力测试{}.html'.format(id + 1))
def index21():
    data_str = df5.to_html()
    c = (Bar().add_xaxis([
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
        "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017",
        "2018"
    ]).add_yaxis("Primary_completion_rate_total",
                 Primary_completion_rate_total,
                 color=Faker.rand_color()).set_global_opts(
                     title_opts=opts.TitleOpts(title=""),
                     datazoom_opts=[
                         opts.DataZoomOpts(),
                         opts.DataZoomOpts(type_="inside")
                     ],
                 ))
    return render_template('results1.html',
                           the_res=data_str,
                           bar_data=c.dump_options(),
                           the_select_region=gdp,
                           the_action="/tochart4",
                           the_title=" Primary_completion_rate_total")
def gdp2019():
    data_str = df4.to_html()
    d = (Bar().add_xaxis([
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
        "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017",
        "2018"
    ]).add_yaxis("GNI_per_capita_Atlas_method",
                 GNI_per_capita_Atlas_method,
                 color=Faker.rand_color()).set_global_opts(
                     title_opts=opts.TitleOpts(title=""),
                     datazoom_opts=[
                         opts.DataZoomOpts(),
                         opts.DataZoomOpts(type_="inside")
                     ],
                 ))
    return render_template('results1.html',
                           the_res=data_str,
                           bar_data=d.dump_options(),
                           the_select_region=gdp,
                           the_action="/tochart3",
                           the_title="GNI_per_capita_Atlas_method ")
def birth_rate2019():
    data_str = df3.to_html()
    e = (Bar().add_xaxis([
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
        "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017",
        "2018"
    ]).add_yaxis("Birth_rate_crude",
                 Birth_rate_crude,
                 color=Faker.rand_color()).set_global_opts(
                     title_opts=opts.TitleOpts(title=""),
                     datazoom_opts=[
                         opts.DataZoomOpts(),
                         opts.DataZoomOpts(type_="inside")
                     ],
                 ))
    return render_template(
        'results1.html',
        the_res=data_str,
        bar_data=e.dump_options(),
        the_title="出生率",
        the_select_region=birth_rate,
        the_action="/tochart2",
    )
예제 #24
0
 def make_relase_year_bar(self):
     """
     生成各年份电影发行量柱状图
     :return:
     """
     # print(get_current_time() + '|-------> 正在生成 各年份电影发行量 图表...')
     # 导入数据并初始化
     csv_path = os.path.abspath(os.path.join(os.path.dirname("__file__"), os.path.pardir, "moviespider", "movie_info_top500.csv"))
     rows = pd.read_csv(csv_path, encoding='utf-8', dtype=str)
     to_drop = ['名称', '导演', '演员', '国别', '类型', '语言', '评分', '评分人数', '五星占比', '四星占比', '三星占比', '二星占比', '一星占比', '短评数',
                '简介']
     res = rows.drop(to_drop, axis=1)
     # 数据分析
     res_by = res.groupby('年份')['年份'].count().sort_values(ascending=False)
     res_by2 = res_by.sort_index(ascending=False)
     type(res_by2)
     years = []
     datas = []
     for k, v in res_by2.items():
         years.append(k)
         datas.append(v)
     # 生成图标
     c = Bar()
     c.add_xaxis(years)
     c.add_yaxis("发行电影数量", datas, color=Faker.rand_color())
     c.set_global_opts(
         title_opts=opts.TitleOpts(title="电影TOP500榜单中 - 各年份电影发行量"),
         datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
     )
     htmlPath = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "analyse_data", "各年份电影发行量.html"))
     pngPath = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "analyse_data", "各年份电影发行量.png"))
     # 生成html
     c.render(htmlPath)
     # 生成png
     # make_snapshot(snapshot, c.render(), pngPath)
     # print(get_current_time() + '|-------> 已生成 各年份电影发行量 图表...')
     return c
예제 #25
0
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.days_attrs)
    .add_yaxis("商家A", Faker.days_values, color=Faker.rand_color())
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-DataZoom(slider-垂直)"),
        datazoom_opts=opts.DataZoomOpts(orient="vertical"),
    )
    
)

c.width = "100%"
put_html(c.render_notebook())
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.days_attrs).add_yaxis(
    "商家A", Faker.days_values, color=Faker.rand_color()).set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-DataZoom(slider+inside)"),
        datazoom_opts=[opts.DataZoomOpts(),
                       opts.DataZoomOpts(type_="inside")],
    ))

c.width = "100%"
put_html(c.render_notebook())
예제 #27
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
예제 #28
0
def action_type_bar(session, charts_type):
    if not session['is_login']:
        return None
    user_id = session['user_id']
    if charts_type == 'gmv':
        cursor.execute("SELECT * FROM t_commodity_sale_info WHERE merchant_id = "+user_id+"  ORDER BY CAST(month_ AS UNSIGNED INTEGER)")

        res = cursor.fetchall()
        xs = list(map(lambda x: x[2], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("gmv变化情况", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="gmv变化情况"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        line = (
            Line().add_xaxis(xs).add_yaxis("gmv变化曲线", ys, is_smooth=True,
                                           areastyle_opts=opts.AreaStyleOpts(opacity=0.5,
                                                                             color=Faker.rand_color()))
                .set_global_opts(
                title_opts=opts.TitleOpts(title="gmv变化曲线"),
                xaxis_opts=opts.AxisOpts(
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
                ).dump_options_with_quotes()
        )
        return [json.loads(bar), json.loads(line)]
    elif charts_type == 'gender':
        cursor.execute("SELECT gender,`count` FROM t_gender_distribute WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        def to_text(l):
            if l[0] == '0.0':
                return ["女性", l[1]]
            elif l[0] == '1.0':
                return ["男性", l[1]]
            else:
                return ["未知", l[1]]
        res = map(to_text, res)
        print(res)
        pie = (
            Pie().add("用户性别分布", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                .set_global_opts(title_opts=opts.TitleOpts(title="用户性别分布"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()
        return [json.loads(pie)]
    elif charts_type == 'area':
        cursor.execute("SELECT area_name,`count` FROM t_area_distribute WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户地域分布情况", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="用户地域分布情况"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户性别分布", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                # .set_global_opts(title_opts=opts.TitleOpts(title="用户地域分布"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()
        return [json.loads(bar), json.loads(pie)]
    elif charts_type == 'age':
        cursor.execute("SELECT age_range,`count` FROM t_age_distribute WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        label = ["未知", "[18-]", "[18,24]", "[25,29]", "[30,34]", "[35,39]", "[40,49]", "[50,60]", "[60+]"]
        xs = list(map(lambda x: label[int(float(x[0]))], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户年龄分布", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="用户年龄分布"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        line = (
            Line().add_xaxis(xs).add_yaxis("用户年龄分布", ys, is_smooth=True,
                                           areastyle_opts=opts.AreaStyleOpts(opacity=0.5,
                                                                             color=Faker.rand_color()))
                .set_global_opts(
                title_opts=opts.TitleOpts(title="用户年龄分布"),
                xaxis_opts=opts.AxisOpts(
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
            ).dump_options_with_quotes()
        )
        return [json.loads(bar), json.loads(line)]
    elif charts_type == 'add_cart':
        cursor.execute("SELECT commodity_brand,`count` FROM add_to_cart_distribute_info WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户添加购物车类别分布", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="用户添加购物车类别分布"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户性别分布", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                # .set_global_opts(title_opts=opts.TitleOpts(title="用户地域分布"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
            ).dump_options_with_quotes()
        return [json.loads(bar), json.loads(pie)]
    elif charts_type == 'add_favorite':
        cursor.execute("SELECT commodity_brand,`count` FROM add_to_favorite_distribute_info WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户添加购物车类别分布", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="用户添加购物车类别分布"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户性别分布", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                # .set_global_opts(title_opts=opts.TitleOpts(title="用户地域分布"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()
        return [json.loads(bar), json.loads(pie)]
    elif charts_type == 'purchase':
        cursor.execute("SELECT commodity_brand,`count` FROM purchase_distribute_info WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户添加购物车类别分布", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="用户添加购物车类别分布"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户性别分布", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                # .set_global_opts(title_opts=opts.TitleOpts(title="用户地域分布"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()
        return [json.loads(bar), json.loads(pie)]
    elif charts_type == 'click':
        cursor.execute("SELECT commodity_brand,`count` FROM click_distribute_info WHERE merchant_id = "+user_id)
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户添加购物车类别分布", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                title_opts=opts.TitleOpts(title="用户添加购物车类别分布"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户性别分布", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                # .set_global_opts(title_opts=opts.TitleOpts(title="用户地域分布"))
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()
        return [json.loads(bar), json.loads(pie)]
예제 #29
0
def action_type_bar2(session,charts_type):
    if not session['is_login']:
        return None
    if charts_type == 'price_month':
        cursor.execute("SELECT month_,`sum(price)` FROM yunying_all_price ORDER BY CAST(month_ AS UNSIGNED INTEGER)")
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("平台整体交易额增长情况", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                toolbox_opts=opts.ToolboxOpts(),
                title_opts=opts.TitleOpts(title="平台整体交易额增长情况"),

                yaxis_opts=opts.AxisOpts(name="交易总额"),
                xaxis_opts=opts.AxisOpts(name="月份"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        line = (
            Line().add_xaxis(xs).add_yaxis("平台整体交易额增长情况", ys, is_smooth=True,
                                           areastyle_opts=opts.AreaStyleOpts(opacity=0.5,
                                                                             color=Faker.rand_color()))
                .set_global_opts(
                title_opts=opts.TitleOpts(title="平台整体交易额增长情况"),
                yaxis_opts=opts.AxisOpts(name="交易总额"),
                xaxis_opts=opts.AxisOpts(
                    name="月份",
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
            ).dump_options_with_quotes()
        )
        return [json.loads(bar), json.loads(line)]
    elif charts_type == 'brand':
        cursor.execute("SELECT brand_id,`count(*)` FROM yunying_brand")
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户购买品牌分布情况", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                toolbox_opts=opts.ToolboxOpts(),
                title_opts=opts.TitleOpts(title="用户购买品牌分布情况"),

                yaxis_opts=opts.AxisOpts(name="交易商品数量"),
                xaxis_opts=opts.AxisOpts(name="品牌"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户购买品牌分布情况", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()

        return [json.loads(bar), json.loads(pie)]
    elif charts_type == 'category':
        cursor.execute("SELECT commodity_brand,`count(*)` FROM yunying_commodity")
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: int(x[1]), res))
        bar = (
            Bar({"theme": ThemeType.MACARONS})
                .add_xaxis(xs).add_yaxis("用户购买商品分类情况", ys)
                .set_series_opts(itemstyle_opts={
                "normal": {
                    "color": Faker.rand_color(),
                    "barBorderRadius": [10, 10, 10, 10],
                    "shadowColor": '#32ca12',
                }}).set_global_opts(
                toolbox_opts=opts.ToolboxOpts(),
                title_opts=opts.TitleOpts(title="用户购买商品分类情况"),

                # yaxis_opts=opts.AxisOpts(name="交易总额"),
                # xaxis_opts=opts.AxisOpts(name="月份"),
                datazoom_opts=[opts.DataZoomOpts(),
                               opts.DataZoomOpts(type_="inside")]).dump_options_with_quotes()
        )
        pie = (
            Pie().add("用户购买品牌分布情况", list(res),
                      radius=["25%", "75%"],
                      center=["50%", "50%"],
                      rosetype="radius",
                      )
                .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        ).dump_options_with_quotes()

        return [json.loads(bar), json.loads(pie)]
    elif charts_type == 'laoguke':
        cursor.execute("SELECT '[0,10]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 10 > `sum(all_price)/count(merchant_id)` AND `sum(all_price)/count(merchant_id)` >= 0 UNION ALL "
                       "SELECT '[10,100]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 100 > `sum(all_price)/count(merchant_id)`AND `sum(all_price)/count(merchant_id)`  >= 10 UNION ALL "
                       "SELECT '[100,500]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 500 > `sum(all_price)/count(merchant_id)`AND `sum(all_price)/count(merchant_id)`  >= 100 UNION ALL "
                       "SELECT '[500,1000]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 1000 > `sum(all_price)/count(merchant_id)`AND `sum(all_price)/count(merchant_id)`  >= 500 UNION ALL "
                       "SELECT '[1000,2000]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 2000 > `sum(all_price)/count(merchant_id)`AND `sum(all_price)/count(merchant_id)`  >= 1000 UNION ALL "
                       "SELECT '[2000,5000]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 5000 > `sum(all_price)/count(merchant_id)`AND `sum(all_price)/count(merchant_id)`  >= 2000 UNION ALL "
                       "SELECT '[5000,10000]' AS qujian,COUNT(merchant_id) FROM laoguke WHERE 10000 > `sum(all_price)/count(merchant_id)`AND `sum(all_price)/count(merchant_id)`  >= 5000 UNION ALL "
                       "SELECT '[10000+]' AS qujian,COUNT(*) FROM laoguke WHERE `sum(all_price)/count(merchant_id)` >= 10000")
        res = cursor.fetchall()
        xs = list(map(lambda x: x[0], res))
        ys = list(map(lambda x: x[1], res))
        c = (
            EffectScatter()
                .add_xaxis(xs)
                .add_yaxis("", ys)
                .set_global_opts(
                title_opts=opts.TitleOpts(title="商家历史gmv分布图"),
                xaxis_opts=opts.AxisOpts(name="gmv区间", splitline_opts=opts.SplitLineOpts(is_show=True)),
                yaxis_opts=opts.AxisOpts(name="商家数量", splitline_opts=opts.SplitLineOpts(is_show=True)),
            )
        ).dump_options_with_quotes()
        line = (
            Line().add_xaxis(xs).add_yaxis("商家历史gmv分布图", ys, is_smooth=True,
                                           areastyle_opts=opts.AreaStyleOpts(opacity=0.5,
                                                                             color=Faker.rand_color()))
                .set_global_opts(
                title_opts=opts.TitleOpts(title=""),
                yaxis_opts=opts.AxisOpts(name="商家数量"),
                xaxis_opts=opts.AxisOpts(
                    name="gmv区间",
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
            ).dump_options_with_quotes()
        )
        return [json.loads(c), json.loads(line)]
예제 #30
0
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker

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)
    #category_gap: 同一系列的柱间距离,默认为类目间距的 20%,可设固定值
    .add_yaxis(
        "series0", y, category_gap=0,
        color=Faker.rand_color()).set_global_opts(title_opts=opts.TitleOpts(
            title="Bar-直方图(颜色区分)")).render("bar_histogram_color.html"))