Hi!请登陆

Python 数据可视化神器—Pyecharts

2023-1-11 118 1/11
能否在 Python 中也能用到 Echarts 的功能呢?寻找中惊喜地发现了 pyecharts,只需在python中安装该模块即可使用。

今日分享主题:Python Pyecharts模块实现数据动态可视化分析

前言

Echarts 是百度开源的一款数据可视化 JS 工具,数据可视化类型十分丰富,但是得通过导入 js 库在 Java Web 项目上运行。

作为工作中常用 Python 的选手,不能不知道这款数据可视化插件的强大。那么,能否在 Python 中也能用到 Echarts 的功能呢?寻找中惊喜地发现了 pyecharts,只需在python中安装该模块即可使用。

安装

常用的pip安装包一键安装pyecharts

# pyecharts安装命令:
python -m pip install pyecharts

 

Python + pyecharts具体应用

结合工作中的项目数据,我选择了 test 项目需求中 hotel_code_new 为 CNSZVS_002,CWSWS_003 对应2019年12个月指标为 RNs 的数据做可视化展示与分析。

1.Hive数据库查询sql

hive_sql内容如下

# sql中所使用的部分语法为hive sql中常规的语法,与mysql有所不同,请注意。
select rrrd1.hotel_code_new as hotel_code_new
      ,dda.natural_date as natural_date
      ,nvl(rrrd.room_nights, 0) as room_nights
 from ( select distinct substr(natural_dt,1,7) as natural_date 
    from dws.dws_test_date_calendar
    where dt_year='2019'
        )dda
        left join 
         (select 'CNSZVS_002' hotel_code_new
            UNION all select  'CWSWS_003' hotel_code_new
      )rrrd1
        left join
         (select  hotel_code_new
                    ,substr(stay_date,1,7) as stay_date
                    ,sum(number_of_room_nights) as room_nights
                from dwm.dwm_test_resvs_rom_daily_df
                where dt='2021-10-24'
                and hotel_code_new in(CNSZVS_002', 'CWSWS_003')
                    and resv_status in('CHECKEDSSSIN','CHECKEDSSSOUT')
                    and substr(stay_date,0,4) = '2019' 
                    group by hotel_code_new,substr(stay_date,1,7)
        )rrrd 
        on dda.natural_date = rrrd.stay_date 
        and rrrd1.hotel_code_new=rrrd.hotel_code_new
        order by rrrd.hotel_code_new;

 

2.Python代码实现—柱状图

from impala.dbapi import connect
import warnings

#数据仓库数据获取准备
def hive_connect(sql):
    warnings.filterwarnings('ignore')
    config_hive_beta = {
        'host': '10.7.0.12',  #hive的host地址
        'port': 10000,    #hive的端口号
        'user': 'hive',    #hive的username
        'password': 'hive',    #hive的password
        'database': 'tmp',     #hive中需要查询的数据库名
        'auth_mechanism': 'PLAIN' #hive的hive-site.xml配置文件中获取
    }
    conn = connect(**config_hive_beta)
    cursor = conn.cursor()
    cursor.execute(sql)
    hive_all_data = cursor.fetchall()
    return hive_all_data


# all_data = hive_connect(hive_sql)
# 通过调用hive_connect方法获取到的数据库查询结果数据如all_data列表所示
all_data = [('CNSZVS_002', '2019-01', 0), ('CNSZVS_002', '2019-02', 0), ('CNSZVS_002', '2019-03', 0),
            ('CNSZVS_002', '2019-04', 0), ('CNSZVS_002', '2019-05', 0), ('CNSZVS_002', '2019-06', 2353),
            ('CNSZVS_002', '2019-07', 2939), ('CNSZVS_002', '2019-08', 5148), ('CNSZVS_002', '2019-09', 3850),
            ('CNSZVS_002', '2019-10', 4973), ('CNSZVS_002', '2019-11', 5467), ('CNSZVS_002', '2019-12', 4742),
            ('CWSWS_003', '2019-01', 5914), ('CWSWS_003', '2019-02', 4434), ('CWSWS_003', '2019-03', 6003),
            ('CWSWS_003', '2019-04', 6611), ('CWSWS_003', '2019-05', 6586), ('CWSWS_003', '2019-06', 5840),
            ('CWSWS_003', '2019-07', 6624), ('CWSWS_003', '2019-08', 7001), ('CWSWS_003', '2019-09', 5792),
            ('CWSWS_003', '2019-10', 6898), ('CWSWS_003', '2019-11', 6944), ('CWSWS_003', '2019-12', 5404)]

# 从pyecharts模块导入柱状图-Bar
from pyecharts import Bar
# 设置横轴行名,这里使用12个月份的英文简称
columns = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# 分别新建2个空list用于存储每个月份对应的RNs的值
CNSZVS_002 = []
CWSWS_003 = []

for i in all_data:
    if i[0] == 'CNSZVS_002':
        CNSZVS_002.append(i[2])
    elif i[0] == 'CWSWS_003':
        CWSWS_003.append(i[2])
    else:
        pass
# 设置柱状图的主标题与副标题
bar = Bar("柱状图", "Test需求—2019年的RNs")
# 添加柱状图的数据及配置项-求平均值、最大值、最小值
bar.add("CNSZVS_002", columns, CNSZVS_002, mark_line=["average"], mark_point=["max", "min"])
bar.add("CWSWS_003", columns, CWSWS_003, mark_line=["average"], mark_point=["max", "min"])
# 在本py文件同级目录下生成名为render.html的本地文件(默认为.html文件)
bar.render()
# 也可设置成指定的路径用于保存html文件
#bar.render(r"D:bar_render.html")

 

生成的柱状效果图是html格式的,可以在浏览器中打开查看,在浏览器中支持下载成图片格式到本地,并且点击图例即可置灰对应的图例,同时隐藏图例对应的柱状图数据,如下图所示。

3.Python代码实现—饼状图

注意:数据准备部分的代码与柱状图一样,这里只展示饼状图特有的代码

# 从pyecharts模块中导入饼图Pie
from pyecharts import Pie
# 设置主标题与副标题,标题设置居中,设置宽度为1000
pie = Pie("饼状图", "Test需求—2019年的RNs", title_pos='left', width=1000)
# 使用add导入数据,设置坐标位置为【20,50】,上方的colums选项取消显示
pie.add("CNSZVS_002", columns, CNSZVS_002, center=[20, 50], is_legend_show=True)
# 使用add导入数据,设置坐标位置为【75,50】,上方的colums选项正常显示
pie.add("CWSWS_003", columns, CWSWS_003, center=[75, 50], is_legend_show=False, is_label_show=True)
# 保存图表
pie.render()

 

饼状效果图展示——隐藏所占百分比

4.Python代码实现—箱型图

# 从pyecharts模块导入箱型图Boxplot
from pyecharts import Boxplot
boxplot = Boxplot("箱型图", "Test需求—2019年的RNs")
x_axis = ['CNSZVS_002', 'CWSWS_003']
y_axis = [CNSZVS_002, CWSWS_003]
# prepare_data方法可以将数据转为嵌套的 [min, Q1, median (or Q2), Q3, max]
yaxis = boxplot.prepare_data(y_axis)
boxplot.add("2019年RNs统计", x_axis, yaxis)
boxplot.render()

    5.Python代码实现—折线图

    from pyecharts import Line
    line = Line("折线图", "Test需求—2019年的RNs")
    # is_label_show属性是设置上方数据是否显示
    line.add("CNSZVS_002", columns, CNSZVS_002, is_label_show=True)
    line.add("CWSWS_003", columns, CWSWS_003, is_label_show=True)
    line.render()

     

    6.Python代码实现—雷达图

    from pyecharts import Radar
    radar = Radar("雷达图", "Test需求—2019年的RNs")
    # 由于雷达图传入的数据得为多维数据,需要将list再进行list转换一次
    CNSZVS_002 = [CNSZVS_002]
    CWSWS_003 = [CWSWS_003]
    # 设置column的最大值,为了雷达图更为直观,这里的月份最大值设置依据真实数据的值来设置,因此各个月份有所不同
    schema_diff = [
        ("Jan", 7000), ("Feb", 5000), ("Mar", 6500),
        ("Apr", 7000), ("May", 7000), ("Jun", 6200),
        ("Jul", 6800), ("Aug", 7200), ("Sep", 6000),
        ("Oct", 7300), ("Nov", 7500), ("Dec", 6000)
    ]
    # 传入坐标
    radar.config(schema_diff)
    radar.add("CNSZVS_002", CNSZVS_002)
    # 一般默认为同一种颜色,这里为了便于区分,需要设置item的颜色
    radar.add("CWSWS_003", CWSWS_003, item_color="#1C86EE")
    radar.render()

      7.Python代码实现—散点图

      from pyecharts import Scatter
      scatter = Scatter("散点图", "Test需求—2019年的RNs")
      # xais_name是设置横坐标名称,这里由于显示问题,还需要将y轴名称与y轴的距离进行设置
      scatter.add("CWSWS_003&CNSZVS_002 RNs的散点分布", CNSZVS_002, CWSWS_003, xaxis_name="CNSZVS_002", yaxis_name="CWSWS_003", yaxis_name_gap=40)
      scatter.render()

       

      总结

      • 准备符合要求的数据及其格式
      • 导入对应图表所使用的包
      • add()方法:主要方法,用于添加图表的数据和设置各种配置项
      • render()方法:用于保存生成的图表

      相关推荐