Python数据可视化大屏最全教程(全)

2022-03-25 0 941

阅读本文大约需要3分钟

Python数据可视化大屏最全教程(全)

主要内容:数据分析。

适用人群:Python初学者,数据分析师,或有志从事数据分析工作的人员。

准备软件:Anaconda(Spyder:代码编译)、Navicat Premium 12(数据库)。

Python数据可视化大屏最全教程(全)

从事IT项目管理这么多年,基本上已经遗弃编程技能,但从2019年开始接触Python,深深地迷上了这门语言,像硬件集成、数据分析,我都会用python来写。晓风想通过本文,让初学者们学会以下内容:

1、Pyecharts图表;

2、连接数据库;

3、大屏看板-监控中心。

今天,我们讲:3、大屏看板如何布局

首先,我们自己先拟个大屏的草稿(如上图),把大屏分割成8个部分(Part0-7)。

Python数据可视化大屏最全教程(全)

大屏内容设计好后,接上文,我们把图表的函数都用代码写出来

from pyecharts import options as opts
from pyecharts.charts import Bar,Gauge,Pie,Page,Funnel,Geo,Scatter3D
import random


def bar(): #柱状图
    cate = ['1月', '2月', '3月', '4月', '5月', '6月']
    c = (      
         Bar()
            .add_xaxis(cate)
            .add_yaxis("订单数", [random.randint(100, 200) for _ in cate])
            .add_yaxis("完成数", [random.randint(50, 100) for _ in cate])
            .set_series_opts(
                             label_opts=opts.LabelOpts(is_show=True,color="#2CB34A")
                             
            )
            .set_global_opts(title_opts=opts.TitleOpts(title="2021年订单推移图",
                                                       title_textstyle_opts=opts.TextStyleOpts(color="#2CB34A"),
                                                       pos_left="5%"),
                             legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="#2CB34A")),
                             xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#2CB34A")),
                             yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#2CB34A"))
                                                     
            )
            .set_colors(["blue", "green"])
            #.render("bar_stack0.html")
    )
    return c


def tab0(name,color): #标题
    c = (Pie().
        set_global_opts(
        title_opts=opts.TitleOpts(title=name,pos_left='center',pos_top='center',
                                title_textstyle_opts=opts.TextStyleOpts(color=color,font_size=20))))
    return c


def tab1(name,color): #标题
    c = (Pie().
        set_global_opts(
        title_opts=opts.TitleOpts(title=name,pos_left='center',pos_top='center',
                                title_textstyle_opts=opts.TextStyleOpts(color=color,font_size=25))))
    return c


def gau():#仪表图
    c = (
        Gauge(init_opts=opts.InitOpts(width="400px", height="400px"))
            .add(series_name="库位利用率", data_pair=[["", 90]])
            .set_global_opts(
            legend_opts=opts.LegendOpts(is_show=False),
            tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{a} <br/>{b} : {c}%"),
            
        )
            #.render("gauge.html")
    )
    return c


def radius():
    cate = ['客户A', '客户B', '客户C', '客户D', '客户E', '其他客户']
    data = [153, 124, 107, 99, 89, 46]
    c=Pie()
    c.add('', [list(z) for z in zip(cate, data)],
            radius=["30%", "75%"],
            rosetype="radius")
    c.set_global_opts(title_opts=opts.TitleOpts(title="客户销售额占比", padding=[1,250],title_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF")),
                      legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="#FFFFFF"),type_="scroll",orient="vertical",pos_right="5%",pos_top="middle")
                      )
    c.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
    c.set_colors(['red',"orange", "yellow", "green", "Cyan", "purple"])
    
    return c


def funnel():
    cate = ['访问', '注册', '加入购物车', '提交订单', '付款成功']
    data = [30398, 15230, 10045, 8109, 5698]
    c = Funnel()
    c.add("用户数", [list(z) for z in zip(cate, data)], 
               sort_='ascending',
               label_opts=opts.LabelOpts(position="inside"))
    c.set_global_opts(title_opts=opts.TitleOpts(title=""))


    return c


def geo():
    city_num = [('武汉',105),('成都',70),('北京',99),
            ('西安',80),('杭州',60),('贵阳',34),
            ('上海',65),('深圳',54),('乌鲁木齐',76),
            ('哈尔滨',47),('兰州',56),('信阳',85)]
    start_end = [('宁波','成都'),('武汉','北京'),('武汉','西安'),
             ('长沙','杭州'),('武汉','贵阳'),('武汉','上海'),
             ('甘肃','深圳'),('北京','乌鲁木齐'),('上海','哈尔滨'),
             ('武汉','兰州'),('西藏','信阳')]
    c = Geo()
    c.add_schema(maptype='china', 
                itemstyle_opts=opts.ItemStyleOpts(color='#323c48', border_color='white'))
    # 4.添加数据
    c.add('', data_pair=city_num, color='white')
    c.add('', data_pair=start_end, type_="lines",label_opts=opts.LabelOpts(is_show=False),
         effect_opts=opts.EffectOpts(symbol="arrow", 
                                     color='gold', 
                                     symbol_size=7))
    c.set_global_opts(
        title_opts = opts.TitleOpts(title=""))
    
    return c


def scatter3D():
    data = [(random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)) for _ in range(80)]
    c = (Scatter3D()
            .add("", data)
            .set_global_opts(
              title_opts=opts.TitleOpts(""),
            )
        )
    

接下来,我们引用Page函数,将所有图表堆积在一个页面中,代码如下

from pyecharts.charts import Page
page = Page() 
page.add(
         tab0("OFFICETOUCH","#2CB34A"), 
         bar(),
         tab1("数据可视化大屏","#2CB34A"),
         gau(),
         radius(),
         funnel(),
         geo(),
         scatter3D()
         )
page.render("datacenter.html")

我们运行下上述两段代码,发现布局是按照从上到下一个个呈现的,到此我们完成了一半的编码

Python数据可视化大屏最全教程(全)

为了将图表按照我们的草稿布局,我们再引用HTML(from bs4 import BeautifulSoup)

from bs4 import BeautifulSoup
with open("datacenter.html", "r+", encoding='utf-8') as html:
    html_bf = BeautifulSoup(html, 'lxml')
    divs = html_bf.select('.chart-container')
    divs[0]["style"] = "width:10%;height:10%;position:absolute;top:0;left:2%;"
    divs[1]["style"] = "width:40%;height:40%;position:absolute;top:12%;left:0;"  
    divs[2]["style"] = "width:35%;height:10%;position:absolute;top:2%;left:30%;"
    divs[3]["style"] = "width:40%;height:40%;position:absolute;top:10%;left:28%;"
    divs[4]["style"] = "width:40%;height:35%;position:absolute;top:12%;left:55%;"
    divs[5]["style"] = "width:30%;height:35%;position:absolute;top:60%;left:2%;"
    divs[6]["style"] = "width:60%;height:50%;position:absolute;top:45%;left:15%;"
    divs[7]["style"] = "width:35%;height:40%;position:absolute;top:50%;left:60%;"
    body = html_bf.find("body")
    body["style"] = "background-image: "  # 背景颜色
    html_new = str(html_bf)
    html.seek(0, 0)
    html.truncate()
    html.write(html_new)
    html.close()

代码中的divs[0]["style"] = "width:10%;height:10%;position:absolute;top:0;left:2%;" 即是我们对Part0的宽度、高度、位置、上边距、左边距的定义,这里我们用百分比以达到屏幕自适应的效果。

最后,我们还可以设置一张背景图,代码合起来如下

from pyecharts import options as opts
from pyecharts.charts import Bar,Gauge,Pie,Page,Funnel,Geo,Scatter3D
import random




def bar(): #柱状图
    cate = ['1月', '2月', '3月', '4月', '5月', '6月']
    c = (      
         Bar()
            .add_xaxis(cate)
            .add_yaxis("订单数", [random.randint(100, 200) for _ in cate])
            .add_yaxis("完成数", [random.randint(50, 100) for _ in cate])
            .set_series_opts(
                             label_opts=opts.LabelOpts(is_show=True,color="#2CB34A")
                             
            )
            .set_global_opts(title_opts=opts.TitleOpts(title="2021年订单推移图",
                                                       title_textstyle_opts=opts.TextStyleOpts(color="#2CB34A"),
                                                       pos_left="5%"),
                             legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="#2CB34A")),
                             xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#2CB34A")),
                             yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#2CB34A"))
                                                     
            )
            .set_colors(["blue", "green"])
            #.render("bar_stack0.html")
    )
    return c


def tab0(name,color): #标题
    c = (Pie().
        set_global_opts(
        title_opts=opts.TitleOpts(title=name,pos_left='center',pos_top='center',
                                title_textstyle_opts=opts.TextStyleOpts(color=color,font_size=20))))
    return c


def tab1(name,color): #标题
    c = (Pie().
        set_global_opts(
        title_opts=opts.TitleOpts(title=name,pos_left='center',pos_top='center',
                                title_textstyle_opts=opts.TextStyleOpts(color=color,font_size=25))))
    return c






def gau():#仪表图
    c = (
        Gauge(init_opts=opts.InitOpts(width="400px", height="400px"))
            .add(series_name="库位利用率", data_pair=[["", 90]])
            .set_global_opts(
            legend_opts=opts.LegendOpts(is_show=False),
            tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{a} <br/>{b} : {c}%"),
            
        )
            #.render("gauge.html")
    )
    return c


def radius():
    cate = ['客户A', '客户B', '客户C', '客户D', '客户E', '其他客户']
    data = [153, 124, 107, 99, 89, 46]
    c=Pie()
    c.add('', [list(z) for z in zip(cate, data)],
            radius=["30%", "75%"],
            rosetype="radius")
    c.set_global_opts(title_opts=opts.TitleOpts(title="客户销售额占比", padding=[1,250],title_textstyle_opts=opts.TextStyleOpts(color="#FFFFFF")),
                      legend_opts=opts.LegendOpts(textstyle_opts=opts.TextStyleOpts(color="#FFFFFF"),type_="scroll",orient="vertical",pos_right="5%",pos_top="middle")
                      )
    c.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
    c.set_colors(['red',"orange", "yellow", "green", "Cyan", "purple"])
    
    return c


def funnel():
    cate = ['访问', '注册', '加入购物车', '提交订单', '付款成功']
    data = [30398, 15230, 10045, 8109, 5698]
    c = Funnel()
    c.add("用户数", [list(z) for z in zip(cate, data)], 
               sort_='ascending',
               label_opts=opts.LabelOpts(position="inside"))
    c.set_global_opts(title_opts=opts.TitleOpts(title=""))


    return c


def geo():
    city_num = [('武汉',105),('成都',70),('北京',99),
            ('西安',80),('杭州',60),('贵阳',34),
            ('上海',65),('深圳',54),('乌鲁木齐',76),
            ('哈尔滨',47),('兰州',56),('信阳',85)]
    start_end = [('宁波','成都'),('武汉','北京'),('武汉','西安'),
             ('长沙','杭州'),('武汉','贵阳'),('武汉','上海'),
             ('甘肃','深圳'),('北京','乌鲁木齐'),('上海','哈尔滨'),
             ('武汉','兰州'),('西藏','信阳')]
    c = Geo()
    c.add_schema(maptype='china', 
                itemstyle_opts=opts.ItemStyleOpts(color='#323c48', border_color='white'))
    # 4.添加数据
    c.add('', data_pair=city_num, color='white')
    c.add('', data_pair=start_end, type_="lines",label_opts=opts.LabelOpts(is_show=False),
         effect_opts=opts.EffectOpts(symbol="arrow", 
                                     color='gold', 
                                     symbol_size=7))
    c.set_global_opts(
        title_opts = opts.TitleOpts(title=""))
    
    return c


def scatter3D():
    data = [(random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)) for _ in range(80)]
    c = (Scatter3D()
            .add("", data)
            .set_global_opts(
              title_opts=opts.TitleOpts(""),
            )
        )
    return c


page = Page() 
page.add(
         tab0("OFFICETOUCH","#2CB34A"), 
         bar(),
         tab1("数据可视化大屏","#2CB34A"),
         gau(),
         radius(),
         funnel(),
         geo(),
         scatter3D()
         )
page.render("datacenter.html")
#os.system("scatter.html")


from bs4 import BeautifulSoup
with open("datacenter.html", "r+", encoding='utf-8') as html:
    html_bf = BeautifulSoup(html, 'lxml')
    divs = html_bf.select('.chart-container')
    divs[0]["style"] = "width:10%;height:10%;position:absolute;top:0;left:2%;"
    divs[1]["style"] = "width:40%;height:40%;position:absolute;top:12%;left:0;"  
    divs[2]["style"] = "width:35%;height:10%;position:absolute;top:2%;left:30%;"
    divs[3]["style"] = "width:40%;height:40%;position:absolute;top:10%;left:28%;"
    divs[4]["style"] = "width:40%;height:35%;position:absolute;top:12%;left:55%;"
    divs[5]["style"] = "width:30%;height:35%;position:absolute;top:60%;left:2%;"
    divs[6]["style"] = "width:60%;height:50%;position:absolute;top:45%;left:15%;"
    divs[7]["style"] = "width:35%;height:40%;position:absolute;top:50%;left:60%;"
    body = html_bf.find("body")
    body["style"] = "background-image: url(bgd.jpg)"  # 背景颜色
    html_new = str(html_bf)
    html.seek(0, 0)
    html.truncate()
    html.write(html_new)
   

效果图如下:

Python数据可视化大屏最全教程(全)

Python数据可视化大屏最全教程(全)

学习到了这里,你是否能独立完成数据可视化的工作了啊?晓风终于不辱使命,向大家完整地介绍了如何使用Python绘制数据可视化大屏。晓风还会继续努力,为大家带来更多有趣、实用、简单的Python功能,愿我们一起成长!

另外两篇教程,如下:

1、Python大屏看板最全教程之Pyecharts图表

https://www.toutiao.com/i6975912477661987336

2、Python大屏看板最全教程之数据库连接

https://www.toutiao.com/i6976121838539735585/

如果觉得有用的话,请帮忙点赞、关注、收藏哦,感谢您的支持!

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Python教程 Python数据可视化大屏最全教程(全) http://www.20zxx.cn/371028/xuexijiaocheng/python.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务