003python模块pyecharts数据可视化的基础学习

json数据格式

什么是json

json是一种轻量级的数据交互格式,本质上是一个带有特定格式的字符串,json就是一种在各个编程语言中流通的数据格式,负责不同编程语言中的数据传递和交互。

在python中进行相互转换

# 导入json模块
import json
data = [{"name": "老王", "age": 18}, {"name": "老李", "age": 20}]

# 通过json.dumps()函数将python数据转换为json数据
json_data = json.dumps(data)
print(f"json_data是:{json_data}, 类型是:{type(json_data)}")
# 通过json.loads()函数将json数据转换为python数据
python_data = json.loads(json_data)
print(f"python_data是:{python_data}, 类型是:{type(python_data)}")
>>>
json_data是:[{"name": "\u8001\u738b", "age": 18}, {"name": "\u8001\u674e", "age": 20}], 类型是:<class 'str'>
python_data是:[{'name': '老王', 'age': 18}, {'name': '老李', 'age': 20}], 类型是:<class 'list'>

pyecharts模块介绍

Echarts 是个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可.而 Python 是门富有表达力的语言,很适合用于数据处理当数据分析遇上数据可视化时pyecharts 诞生了

pyecharts快速入门

基础折线图

from pyecharts.charts import Line

# 得到折线图对象
line = Line()

# 给折线图对象添加x轴数据
line.add_xaxis(['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋'])

# 给折线图对象添加y轴数据
line.add_yaxis('商家A', [5, 20, 36, 10, 75])
# 设置全局配置项set_global_opts()
line.set_global_opts(
    title_opts=TitleOpts(title='销售情况', pos_left='center', pos_bottom='bottom'),
    legend_opts=LegendOpts(is_show=True), # 显示图例
    toolbox_opts=ToolboxOpts(is_show=True), # 显示工具箱
    visualmap_opts=VisualMapOpts(is_show=True), # 显示视觉映射配置项
    xaxis_opts={'name': '商品'}, # 设置x轴名称
    yaxis_opts={'name': '销量'}, # 设置y轴名称
)
# 通过render()函数生成折线图
line.render('line.html')

相关控制
image.png

折线图案例

20年新冠确诊人数对比折线图

import get_data as gd
from pyecharts.charts import Line
from pyecharts.options import TitleOpts
from pyecharts.options import LabelOpts
us_path = "D:/project_code_file/python/python基础学习/study/044案例1数据可视化/折线图数据/美国.txt"
jp_path = "D:/project_code_file/python/python基础学习/study/044案例1数据可视化/折线图数据/日本.txt"
ind_path = "D:/project_code_file/python/python基础学习/study/044案例1数据可视化/折线图数据/印度.txt"
us_error_str = "jsonp_1629344292311_69436("
jp_error_str = "jsonp_1629350871167_29498("
ind_error_str = "jsonp_1629350745930_63180("
us_x_data, us_y_data = gd.getdata(us_path, us_error_str)
jp_x_data, jp_y_data = gd.getdata(jp_path, jp_error_str)
ind_x_data, ind_y_data = gd.getdata(ind_path, ind_error_str)
#获取图表对象
line = Line()
line.add_xaxis(us_x_data) # x轴共用
line.add_xaxis(jp_x_data)
line.add_xaxis(ind_x_data)
line.add_yaxis("美国确诊人数", us_y_data, label_opts=LabelOpts(is_show=False)) #添加美国的y轴数据
line.add_yaxis("日本确诊人数", jp_y_data, label_opts=LabelOpts(is_show=False)) #添加日本的y轴数据
line.add_yaxis("印度确诊人数", ind_y_data, label_opts=LabelOpts(is_show=False)) #添加印度的y轴数据
#设置全局配置项
line.set_global_opts(
    title_opts=TitleOpts(title="2020年美日印新冠确诊人数对比折线图", pos_left='center', pos_bottom='bottom'),
)
# 调用render()方法生成本地HTML文件
line.render("新冠确诊人数.html")

渲染出来的页面:
image.png

地图可视化案例

河南省疫情地图绘制

f.close()
# print(type(data))
dict_data = json.loads(data)    # 将字符串转换为字典
# 获取全部数据之后,根据数据的层级关系,取到河南的数据
henan_city_data_list = dict_data["areaTree"][0]["children"][3]["children"]
print(type(henan_city_data_list))
# 遍历列表获取每一个市的数据
data_list = []
for city_data in henan_city_data_list:
    city_name = city_data["name"] + "市"
    city_confirm = city_data["total"]["confirm"]
    data_list.append((city_name, city_confirm))
data_list.append(("济源市", 5))
# 获取地图对象
map = Map()
# 添加数据
map.add("河南疫情图", data_list, "河南")
# 设置全局配置项
map.set_global_opts(
    title_opts=TitleOpts(title="河南疫情图"),
    visualmap_opts=VisualMapOpts(
        is_show=True,  # 是否显示视觉映射配置
        is_piecewise=True,  # 是否分段显示
        pieces=[
            {"min": 1, "max": 9, "label": "1-9人", "color": "#FFFF99"},
            {"min": 10, "max": 99, "label": "10-99人", "color": "#FF9966"},
            {"min": 100, "max": 999, "label": "100-999人", "color": "#FF6666"},
            {"min": 1000, "max": 9999, "label": "1000-9999人", "color": "#CC3333"},
            {"min": 10000, "label": "10000人以上", "color": "#990033"},
        ]
    )
)

# 生成html文件
map.render("河南疫情图.html")

渲染出来的页面:
image.png

动态柱状图案例

GDP全球动态排行

import time
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
# 导入主题
from pyecharts.globals import ThemeType

data_file_name = "D:/project_code_file/python/python基础学习/study/044案例1数据可视化/动态柱状图数据/1960-2019全球GDP数据.csv"
f = open(data_file_name, encoding='gbk')
data_lines = f.readlines()
# 关闭文件
f.close()
data_lines.pop(0)
# print(data_lines)
# 定义一个字典对象
data_dict = {}

# 定义一个时间线对象
timeline = Timeline({"Theme": ThemeType.LIGHT})
# 遍历数据,将数据存储到字典中
for one_line in data_lines:
    # 去掉换行符
    one_line = one_line.strip('\n')
    # 用逗号分隔数据
    line_year = (int)(one_line.split(',')[0]) # 年份
    line_country = one_line.split(',')[1]   # 国家
    line_gdp = (float)(one_line.split(',')[2]) # GDP
    # 判断字典中是否存在指定的key
    try:
        data_dict[line_year].append([line_country, line_gdp]) # 如果key不存在会报错
    except KeyError:
        data_dict[line_year] = []   # 解决办法:如果key不存在,就创建一个空列表
        data_dict[line_year].append([line_country, line_gdp])
# 排序年份
sorted_year_list = sorted(data_dict.keys())
# print(sorted_year_list)
for year in sorted_year_list:
    data_dict[year].sort(key=lambda x: x[1], reverse=True)
    # 取出前八位
    top8_list = data_dict[year][: 8]
    x_data = []
    y_data = []
    for one in top8_list:
        x_data.append(one[0])   # 国家
        y_data.append(one[1] / 100000000)   # GDP
    # 构建柱状图对象
    bar = Bar()
    # x和y轴的数据反转
    x_data.reverse()
    y_data.reverse()
    # 添加数据
    bar.add_xaxis(x_data)
    bar.add_yaxis('GDP(亿)', y_data, label_opts=LabelOpts(position='right'))
    # 反转轴体
    bar.reversal_axis()
    # 设置每一年图表的标题
    bar.set_global_opts(title_opts=TitleOpts(title=f'{year}年全球GDP排名(前八)'))
    # 添加到时间线对象中
    timeline.add(bar, f'{year}年')

# 设置时间线自动播放
timeline.add_schema(
    play_interval=300,
    is_auto_play=True,
    is_loop_play=False,
    is_timeline_show=True,
)
# 绘图
timeline.render('1960-2019全球GDP动态柱状图.html')

渲染出来的页面:
image.png

总结

总的来说,模块的使用并不难,对于初学的我来说,难的是相关原生数据的提取,还有后续数据的处理
继续加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cles8it

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值