当前位置:   article > 正文

pyecharts数字大屏_基于Pyecharts可视化大屏案例一(3)

pyecharts数据可视化大屏案例

    上两篇文章《基于Pyecharts可视化大屏案例一(1)》《基于Pyecharts可视化大屏案例一(2)》已经为大家详细展示了大屏大致的制作过程以及可视化大屏的布局,接下来继续完善。我们先来回顾下完整的精美大屏:

af17f5522fe105ef34f179880f20410a.png

         请看下本文在上两文基础上制作左上图形的最终效果:

26ccfc01e669ae165b93f60d749320ea.png

        放大展示(注意放大后需要F5刷新一下):

1950c1fd2f029e31dd6ee0432b5ed0e8.png

        接下来,就开始漫长的......

1.  加载一箩筐的库

from pyecharts.charts import Page,Bar,Line,Grid,Pieimport pyecharts.options as optsfrom pyecharts.globals import ThemeTypefrom pyecharts.faker import Fakerfrom pyecharts.commons.utils import JsCodeimport pandas as pdimport numpy as npimport randomfrom bs4 import BeautifulSoup

2.  生成随机数据

names = ['店员_'+str(i) for i in range(1,51)] #生成n个店员的名字sales = [random.randint(10,100) for _ in range(50)] #随机生成n个数字,代表店员销售额df = pd.DataFrame() #生成一个空DataFrame()df['店员'] = names df['销售额'] = salesdf.sort_values(by='销售额',ascending=False,inplace=True) #按销售额从小到大排序data_pair = [] #生成画图需要的数据格式for i,j in zip(df['店员'],df['销售额']):    list_ = [i,j]    data_pair.append(list_)

3.  不加任何参数绘制饼图

# 画图pie = (    Pie()    .add(        series_name="店员销售额",        data_pair=data_pair,    )).render('test.html')

fed9b97d62cae32fd20b2df936b9ca02.png

4.  去掉legend和设置标题

# 画图pie = (    Pie()    .add(        series_name="店员销售额",        data_pair=data_pair,    )    .set_global_opts(        title_opts=opts.TitleOpts(            title="导购员成交销售额",            pos_left="center",            pos_top="0%",            title_textstyle_opts=opts.TextStyleOpts(color="pink",font_size = 20,),        ),        legend_opts=opts.LegendOpts(            is_show = False,        ),    )).render('test.html')

a033c5a595d06e65520fc714f2b7b24f.png

5.  设置饼图类型为南丁格尔玫瑰图、圆心位置,以及空心的大小

# 画图pie = (    Pie()    .add(        series_name="店员销售额",        data_pair=data_pair,        rosetype="radius", #类型为南丁格尔玫瑰图        radius=["10%","60%"],        center=["center", "center"], #设置圆心位置    )    .set_global_opts(        title_opts=opts.TitleOpts(            title="导购员成交销售额",            pos_left="center",            pos_top="0%",            title_textstyle_opts=opts.TextStyleOpts(color="pink",font_size = 20,),        ),        legend_opts=opts.LegendOpts(            is_show = False,        ),    )).render('test.html')

d82d1a821eae663aaba7a04bbb7eddb6.png

6.  设置标签,加上百分比

# 画图pie = (    Pie()    .add(        series_name="店员销售额",        data_pair=data_pair,        rosetype="radius", #类型为南丁格尔玫瑰图        radius=["10%","60%"],        center=["center", "center"], #设置圆心位置    )    .set_global_opts(        title_opts=opts.TitleOpts(            title="导购员成交销售额",            pos_left="center",            pos_top="0%",            title_textstyle_opts=opts.TextStyleOpts(color="pink",font_size = 20,),        ),        legend_opts=opts.LegendOpts(            is_show = False,        ),    )    .set_series_opts(        label_opts=opts.LabelOpts(formatter="{b}: {c}万"),        tooltip_opts=opts.TooltipOpts(            trigger="item", formatter="{a} {b}: {c}万 ({d}%)"        ),    )).render('test.html')

cfac28b834ccbe1f544a7dde54988e97.png

7.  通过grid()设置背景

# 画图pie = (    Pie()    .add(        series_name="店员销售额",        data_pair=data_pair,        rosetype="radius", #类型为南丁格尔玫瑰图        radius=["10%","60%"],        center=["center", "center"], #设置圆心位置    )    .set_global_opts(        title_opts=opts.TitleOpts(            title="导购员成交销售额",            pos_left="center",            pos_top="0%",            title_textstyle_opts=opts.TextStyleOpts(color="pink",font_size = 20,),        ),        legend_opts=opts.LegendOpts(            is_show = False,        ),    )    .set_series_opts(        label_opts=opts.LabelOpts(formatter="{b}: {c}万"),        tooltip_opts=opts.TooltipOpts(            trigger="item", formatter="{a} {b}: {c}万 ({d}%)"        ),    ))grid = (    Grid(        init_opts=opts.InitOpts(            theme =  ThemeType.WONDERLAND #设置主题        )    )    .add(pie, grid_opts=opts.GridOpts(pos_left='0%',)) #调整位置).render('test.html')

96c0efe1d8ca18f9bab6697638edaf4e.png

8.  添加到大屏上

def get_grid_3():    names = ['店员_'+str(i) for i in range(1,101)] #生成100个店员的名字    sales = [random.randint(10,100) for _ in range(100)] #随机生成100个数字,代表店员销售额    df = pd.DataFrame() #生成一个空DataFrame()    df['店员'] = names     df['销售额'] = sales    df.sort_values(by='销售额',ascending=False,inplace=True) #按销售额从小到大排序    data_pair = [] #生成画图需要的数据格式    for i,j in zip(df['店员'],df['销售额']):        list_ = [i,j]        data_pair.append(list_)        # 画图    pie = (        Pie()        .add(            series_name="店员销售额",            data_pair=data_pair,            rosetype="radius", #类型为南丁格尔玫瑰图            radius=["10%","60%"],            center=["center", "center"], #设置圆心位置        )        .set_global_opts(            title_opts=opts.TitleOpts(                title="导购员成交销售额",                pos_left="center",                pos_top="0%",                title_textstyle_opts=opts.TextStyleOpts(color="pink",font_size = 20,),            ),            legend_opts=opts.LegendOpts(                is_show = False,            ),        )        .set_series_opts(            label_opts=opts.LabelOpts(formatter="{b}: {c}万"),            tooltip_opts=opts.TooltipOpts(                trigger="item", formatter="{a} {b}: {c}万 ({d}%)"            ),        )    )        grid = (        Grid(            init_opts=opts.InitOpts(                theme =  ThemeType.WONDERLAND #设置主题            )        )        .add(pie, grid_opts=opts.GridOpts(pos_left='0%',)) #调整位置    )        return griddef get_page():    grid3 = get_grid_3()        page = (        Page()        .add(grid3)    )    return pageif __name__ == "__main__":    page = get_page()    page.render('test.html')        with open("test.html", "r+", encoding='utf-8') as html:            html_bf = BeautifulSoup(html, 'lxml')        divs = html_bf.select('.chart-container')        divs[0]['style'] = "width:550px;height:400px;position:absolute;top:540px;left:30px;border-style:solid;border-color:#444444;border-width:0px;"                body = html_bf.find("body")        body["style"] = "background-color:#07645D;" #设置网页背景颜色        div_title="
\n2020年销售数据分析
" #修改页面背景色、追加标题 body.insert(0,BeautifulSoup(div_title,"lxml").div) html_new = str(html_bf) html.seek(0, 0) html.truncate() html.write(html_new) html.close()

88c0344a0d5dde042820d06dbbacf6b5.png

9.  最后附上含三张图片的可视化大屏代码

def get_grid_1():    year = list(range(2004,2021)) #年份    random_data_1 = [random.randint(1000,10000) for _ in range(17) ] #生成17个随机整数    random_data_2 = [random.randint(100,1000) for _ in range(17) ] #生成17个随机整数    r1 = [round((random_data_1[i]-random_data_1[i-1])/random_data_1[i],2) for i in range(len(random_data_1))[1:]] #计算增长率,并取2位小数点    r2 = [round((random_data_2[i]-random_data_2[i-1])/random_data_2[i],2) for i in range(len(random_data_2))[1:]] #计算增长率,并取2位小数点    # 柱图    bar = (        Bar()        .add_xaxis(year)        .add_yaxis('销售额',random_data_1,yaxis_index=0,gap='10%')        .add_yaxis('订单量',random_data_2,yaxis_index=1,gap='10%')        .extend_axis(              #添加一个描绘订单量的坐标轴            yaxis=opts.AxisOpts(                name = '订单量\n(万件)',                position = 'right', #设置坐标轴在画布右侧                min_ = 0, #设置y刻度的最小值                max_ = 1300, #设置y刻度的最小值                offset = 60, #设置Y轴偏移                axisline_opts=opts.AxisLineOpts(                    linestyle_opts=opts.LineStyleOpts(color="#FFB8B8")                ),            )        )        .extend_axis(               #添加一个描绘增长率的坐标轴            yaxis=opts.AxisOpts(                name = '增长率',                position="left",   #设置坐标轴在画布左侧                min_ = -5, #设置y刻度的最小值                max_ = 5,#设置y刻度的最大值                axisline_opts=opts.AxisLineOpts(                    linestyle_opts=opts.LineStyleOpts(color="#CCCC00")                ),            )        )        .set_global_opts(            yaxis_opts=opts.AxisOpts(                name = '销售额\n(万元)',                position="right", #设置描绘销售额的坐标轴在画布右侧                axisline_opts=opts.AxisLineOpts(                    linestyle_opts=opts.LineStyleOpts(color="#EEAEEE")                ),            ),             title_opts=opts.TitleOpts(                title="历年订货额/订单量增长情况",                pos_left = 'center',                pos_top = '0px',                # 设置主标题字体、颜色、大小等                title_textstyle_opts = opts.TextStyleOpts(                     #文字颜色                     color='#66FFB3',                      #文字风格,可选:normal(正常)、italic(斜体)、oblique(斜体)                     font_style='normal',                      #主标题文字字体的粗细,可选:'normal''bold''bolder''lighter'                     font_weight='bold',                     #文字的字体系列,还可以是 'serif' , 'monospace', 'Arial', 'Courier New', 'Microsoft YaHei', ...                     font_family='Arial',                     # 文字的字体大小                     font_size = 25,                )            ),            legend_opts=opts.LegendOpts( #将标签设置在左边居中,并纵向排列                is_show=True,                 pos_left="left",                 orient="vertical",                pos_top = 'center',                textstyle_opts = opts.TextStyleOpts(                                          font_size = 10,  # 标签字体大小                                                 )            ),            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), #设置提示框            datazoom_opts=opts.DataZoomOpts(                range_start = 70,                range_end = 100,            ),        )    )    #线图    line = (        Line()        .add_xaxis(['2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'])        .add_yaxis('销增长率',r1,yaxis_index=2,itemstyle_opts=opts.ItemStyleOpts(color='green'))        .add_yaxis('订增长率',r2,yaxis_index=2,itemstyle_opts=opts.ItemStyleOpts(color='#FF4D4D'))    )    # 合并两个图    overlap_ = bar.overlap(line)    grid = (        Grid(            init_opts=opts.InitOpts(                width = '1500px', # 设置画布宽                height = '800px', #设置画布高        #             bg_color = '#004B66', # 背景颜色设置                theme =  ThemeType.WONDERLAND #设置主题            )        )        .add(overlap_,              opts.GridOpts(                 pos_left="10%", #调整左边轴线与画布的距离                 pos_right="13%" #调整右边边轴线与画布的距离             ),              is_control_axis_index=True,        )    )        return griddef get_grid_2():    names = ['门店_'+str(i) for i in range(1,31)] #生成30个门店的名字    sales = [random.randint(1000,10000) for _ in range(30)] #随机生成30个数字,代表门店销售额    df = pd.DataFrame() #生成一个空DataFrame()    df['店名'] = names     df['销售额'] = sales    df.sort_values(by='销售额',ascending=True,inplace=True) #按销售额从小到大排序    # 修改店名(加上排名显示)    new_names = []     for name,i in zip(df['店名'],[i for i in range(30,0,-1)]):         new_names.append(name+'(第'+str(i)+'名)')    df['店名'] = new_names        # 画图    bar = (        Bar()        .add_xaxis(df['店名'].tolist())        .add_yaxis("门店销售额(万元)", df['销售额'].tolist())        .reversal_axis() #旋转XY轴        .set_global_opts(            xaxis_opts=opts.AxisOpts(                max_ = 11000,                axislabel_opts  = opts.LabelOpts(                    color = '#BFBFBF' # 设置X轴标签颜色                ),            ),            yaxis_opts=opts.AxisOpts(                axislabel_opts  = opts.LabelOpts(                    font_size = 15,                    color = '#BFBFBF' # 设置Y轴标签颜色                ),            ),            legend_opts=opts.LegendOpts(                is_show=True,                 pos_left="center",                 orient="vertical",                textstyle_opts = opts.TextStyleOpts(                      color  = '#FFDA85',                    # 文字的字体大小                    font_size = 20,                                                   )            ),            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),            datazoom_opts=opts.DataZoomOpts(                type_='inside',  #将拖拉框隐藏                orient='vertical', #将拖拉框垂直放置,即按Y轴拖拉                range_start = 60, #拖拉起始位置(百分比)                range_end = 100, #拖拉结束位置(百分比)            ),        )        .set_series_opts(            label_opts=opts.LabelOpts(position="right"), #设置标签值的位置            markline_opts=opts.MarkLineOpts(                data=[opts.MarkLineItem(x=df['销售额'].mean(), name="均值")], #添加均值线                linestyle_opts=opts.LineStyleOpts(color="#00CC99")             ),        )    )        # 创建一个grid    grid = (        Grid(            init_opts=opts.InitOpts(                theme =  ThemeType.WONDERLAND #设置主题            )        )        .add(bar, grid_opts=opts.GridOpts(pos_left='20%',)) #调整位置,将店名都显示出来    )       return griddef get_grid_3():    names = ['店员_'+str(i) for i in range(1,101)] #生成100个店员的名字    sales = [random.randint(10,100) for _ in range(100)] #随机生成100个数字,代表店员销售额    df = pd.DataFrame() #生成一个空DataFrame()    df['店员'] = names     df['销售额'] = sales    df.sort_values(by='销售额',ascending=False,inplace=True) #按销售额从小到大排序    data_pair = [] #生成画图需要的数据格式    for i,j in zip(df['店员'],df['销售额']):        list_ = [i,j]        data_pair.append(list_)        # 画图    pie = (        Pie()        .add(            series_name="店员销售额",            data_pair=data_pair,            rosetype="radius", #类型为南丁格尔玫瑰图            radius=["10%","60%"],            center=["center", "center"], #设置圆心位置        )        .set_global_opts(            title_opts=opts.TitleOpts(                title="导购员成交销售额",                pos_left="center",                pos_top="0%",                title_textstyle_opts=opts.TextStyleOpts(color="pink",font_size = 20,),            ),            legend_opts=opts.LegendOpts(                is_show = False,            ),        )        .set_series_opts(            label_opts=opts.LabelOpts(formatter="{b}: {c}万"),            tooltip_opts=opts.TooltipOpts(                trigger="item", formatter="{a} {b}: {c}万 ({d}%)"            ),        )    )        grid = (        Grid(            init_opts=opts.InitOpts(                theme =  ThemeType.WONDERLAND #设置主题            )        )        .add(pie, grid_opts=opts.GridOpts(pos_left='0%',)) #调整位置    )        return griddef get_page():    grid1 = get_grid_1()    grid2 = get_grid_2()    grid3 = get_grid_3()        page = (        Page()        .add(grid1)        .add(grid2)        .add(grid3)    )    return pageif __name__ == "__main__":    page = get_page()    page.render('my_first_pycharts.html')        with open("my_first_pycharts.html", "r+", encoding='utf-8') as html:        html_bf = BeautifulSoup(html, 'lxml')        divs = html_bf.select('.chart-container')        divs[0]['style'] = "width:750px;height:400px;position:absolute;top:120px;left:550px;border-style:solid;border-color:#444444;border-width:0px;"        divs[1]['style'] = "width:550px;height:400px;position:absolute;top:120px;left:30px;border-style:solid;border-color:#444444;border-width:0px;"        divs[2]['style'] = "width:550px;height:400px;position:absolute;top:540px;left:30px;border-style:solid;border-color:#444444;border-width:0px;"        body = html_bf.find("body")        body["style"] = "background-color:#07645D;" #设置网页背景颜色        div_title="
\n2020年销售数据分析
" #修改页面背景色、追加标题 body.insert(0,BeautifulSoup(div_title,"lxml").div) html_new = str(html_bf) html.seek(0, 0) html.truncate() html.write(html_new) html.close()

688bc262a44c7645615a34e4d26c6b5c.png

THE END!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/659786
推荐阅读
相关标签
  

闽ICP备14008679号