Pyecharts

Pyecharts

1.JSON数据格式

1.JSON的说明

①JSON是一种轻量级的数据交互格式,可以按照JSON指定的格式去组织和封装数据

②JSON本质上是一个带有特定格式的字符串

③JSON就是一种在各个编程语言中流通的数据格式,负责不同编程语言中的数据传递和交互

# json数据的格式可以是:本身是字典 
{"name":"admin","age":18} 

# 也可以是:列表中的元素是字典
[{"name":"admin","age":18},{"name":"root","age":16},{"name":"张三","age":20}] 
2.JSON格式数据转换

①Python语言使用JSON有很大优势,因为JSON无非就是一个单独的字典或一个内部元素都是字典的列表,所以JSON可以直接和Python的字典或列表进行无缝转换。

②dumps(data, ensure_ascii=False):将python格式转换为json字符串,如果数据中带有中文,需要设置ensure_ascii为False

③loads(data):将json字符串转换为python格式

# 先导入json的包
import json
# json.dumps(data,ensure_ascii=False):将Python数据转化为JSON字符串,如果数据中带有中文,需要设置ensure_ascii为False,不适用asc码去转换数据而是直接输出
# 将python的列表转换为字符串
data = [{'name': '张大三', 'age': 11}, {'name': '小虎', 'age': 12}, {'name': '王大锤', 'age': 13}]
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)  # [{"name": "张大三", "age": 11}, {"name": "小虎", "age": 12}, {"name": "王大锤", "age": 13}]
# 将python的字典转换为字符串
dic = {'name': '黄景瑜', 'age': 29}
json_str_dic = json.dumps(dic, ensure_ascii=False)
print(json_str_dic)
# 将json字符串变回python的列表
s = '[{"name": "张大三", "age": 11}, {"name": "小虎", "age": 12}, {"name": "王大锤", "age": 13}]'
pytype = json.loads(s)
print(pytype)  # [{'name': '张大三', 'age': 11}, {'name': '小虎', 'age': 12}, {'name': '王大锤', 'age': 13}]
s1 = '{"name": "黄景瑜", "age": 29}'
print(json.loads(s1))  # {'name': '黄景瑜', 'age': 29}

2.Pycharts模块介绍

①如果想要做出数据可视化效果图, 可以借助pyecharts模块来完成

②画廊网址:https://gallery.pyecharts.org/#/README

③pyecharts官网:https://pyecharts.org/#/zh-cn/

3·Pycharts–Line折线图

1.折线图的使用步骤
步骤:
1.导包
2.创建对象
3.设置x轴与y轴参数
4.全局配置(也需要导包)
5.生成图像
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts
line = Line()
line.add_xaxis(['中国', '美国', '英国'])
line.add_yaxis('GDP', [30, 20, 10])
line.set_global_opts()
line.render()

也可以用链式调用的方式
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts
line = (
    Line()
    .add_xaxis(['中国', '美国', '日本'])
    .add_yaxis('gdp', [30, 20, 10])
    .set_global_opts(
        title_opts=TitleOpts(title='GDP图解')
    )
)
line.render('render1.html')
2.全局配置项
# 1.使用步骤
1.导包from pyecharts.options import 类名
2.使用:line.set_global_opts(参数1,参数2)
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts

# 2.在pyecharts可以查看全局配置项的参数

# 3.案例
line.set_global_opts(
    # 变量名=对应类(参数)
    # title_opts=TitleOpts():设置标题,需要先导入标题包:from pyecharts.options import TitleOpts
    # TitleOpts()参数设置:可以按ctrl+p进行查看,title='标题名称',pos_left(上下左右都有)='center、距离左侧百分比或数字'
    title_opts=TitleOpts(title='GDP展示', pos_left='center', pos_bottom='1%'),
    # legend_opts=LegendOpts():图例展示(图例是默认展示),要先导入标题包:from pyecharts.options import LegendOpts
    # LegendOpts()参数设置:is_show=True是否展示
    legend_opts=LegendOpts(is_show=True),
    # toolbox_opts=ToolboxOpts():工具箱展示,先导入标题包:from pyecharts.options import ToolboxOpts
    toolbox_opts=ToolboxOpts(is_show=True),
    # visualmap_opts=VisualMapOpts():映射选项,要先导入标题包:from pyecharts.options import VisualMapOpts
    visualmap_opts=VisualMapOpts(is_show=True)
)
3.系列配置项

①可以通过对象.set_series_opts()进行统一设置,也可以在使用对象添加数据时进行设置

4.案例
1.引入案例
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts
# 创建一个折线图对象
line = Line()
# add_xaxis(列表):给折线图x轴添加数据
line.add_xaxis(['中国', '美国', '英国'])
# add_yaxis('纵坐标含义',[纵坐标数值列表]):给折线图y轴添加数据
line.add_yaxis('GDP', [30, 20, 10])
# 全局配置项
line.set_global_opts(
    # 变量名=对应类(参数)
    # title_opts=TitleOpts():设置标题,需要先导入标题包:from pyecharts.options import TitleOpts
    # TitleOpts()参数设置:可以按ctrl+p进行查看,title='标题名称',pos_left(上下左右都有)='center、距离左侧百分比或数字'
    title_opts=TitleOpts(title='GDP展示', pos_left='center', pos_bottom='1%'),
    # legend_opts=LegendOpts():图例展示(图例是默认展示),要先导入标题包:from pyecharts.options import LegendOpts
    # LegendOpts()参数设置:is_show=True是否展示
    legend_opts=LegendOpts(is_show=True),
    # toolbox_opts=ToolboxOpts():工具箱展示,先导入标题包:from pyecharts.options import ToolboxOpts
    toolbox_opts=ToolboxOpts(is_show=True),
    # visualmap_opts=VisualMapOpts():映射选项,要先导入标题包:from pyecharts.options import VisualMapOpts
    visualmap_opts=VisualMapOpts(is_show=True)
)
# render():将代码生成图像
line.render()
2.新冠肺炎疫情折线图
import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LabelOpts

# 读取json文件
us_file = open('E:/资料/Python/资料/可视化案例数据/折线图数据/美国.txt', 'r', encoding='utf=8')
us_json_data = us_file.read()
jp_file = open('E:/资料/Python/资料/可视化案例数据/折线图数据/日本.txt', 'r', encoding='utf=8')
jp_json_data = jp_file.read()
in_file = open('E:/资料/Python/资料/可视化案例数据/折线图数据/印度.txt', 'r', encoding='utf=8')
in_json_data = in_file.read()
# 截取json内容
us_json_data = us_json_data.replace('jsonp_1629344292311_69436(', '')
jp_json_data = jp_json_data.replace('jsonp_1629350871167_29498(', '')
in_json_data = in_json_data.replace('jsonp_1629350745930_63180(', '')
us_json_data = us_json_data[:-2]
jp_json_data = jp_json_data[:-2]
in_json_data = in_json_data[:-2]
# 将json转换为python类型数据
us_py_data = json.loads(us_json_data)
jp_py_data = json.loads(jp_json_data)
in_py_data = json.loads(in_json_data)
# 从数据中找出日期和确诊人数
us_date_data = us_py_data['data'][0]['trend']['updateDate'][:314]
jp_date_data = jp_py_data['data'][0]['trend']['updateDate'][:314]
in_date_data = in_py_data['data'][0]['trend']['updateDate'][:314]
us_count_data = us_py_data['data'][0]['trend']['list'][0]['data'][:314]
jp_count_data = jp_py_data['data'][0]['trend']['list'][0]['data'][:314]
in_count_data = in_py_data['data'][0]['trend']['list'][0]['data'][:314]
# 创建折线图对象
line = Line()
line.add_xaxis(us_date_data)
line.add_yaxis('美国确诊人数', us_count_data)
line.add_yaxis('日本确诊人数', jp_count_data)
line.add_yaxis('印度确诊人数', in_count_data)
line.set_global_opts(
    title_opts=TitleOpts(title='美日印新冠肺炎确认数据图', pos_left='center', pos_bottom='1%')
)
# 也可以直接在对应的y坐标上设置来隐藏某一个坐标的:line.add_yaxis('印度确诊人数', in_count_data,label_opts=LabelOpts(is_show=False))
line.set_series_opts(
    label_opts=LabelOpts(is_show=False)
)
line.render('新冠肺炎疫情折线图.html')
us_file.close()
jp_file.close()
in_file.close()

4.Pycharts–Map地图

①data数据为列表,列表中存放元组

②add中最后一个参数可以设置地图类型,默认为’china’

③pieces为列表,列表中存放字典

1.基础地图
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts

map = Map()
data = [('北京', 99), ('上海', 199), ('湖南', 299), ('台湾', 399), ('山东', 499), ('陕西', 9999)]
# add('地图名称',数据项,地图类型(默认'china')):添加数据,数据的格式是一个列表,里面包含多个元组('坐标点名称',数值)
map.add('地图', data_pair=data, 'china')
map.set_global_opts(
    visualmap_opts=VisualMapOpts(
        		  is_show=True, 
        		  is_piecewise=True,
                   pieces=[{'min': 1, 'max': 9, 'label': '1 - 9人', 'color': '#CCFFFF'},
                           {'min': 10, 'max': 99, 'label': '10-99人', 'color': '#FFFF99'},
                           {'min': 100, 'max': 499, 'label': '100-499人', 'color': '#FF9966'},
                           {'min': 500, 'max': 999, 'label': '500-999人', 'color': '#FF6666'},
                           {'min': 999, 'max': 9999, 'label': '999-9999人', 'color': '#CC3333'},
                           {'min': 10000, 'label': '10000人以上', 'color': '#990033'}
                           ]
                           )
    # 由于显示的数量颜色不准确,因此可以使用is_piecewise=True来开启手动矫正范围
    # pieces来设置具体颜色,是一个列表,列表中是多个字典,[{'min': 最小值, 'max': 最大值, 'label': '标签提示', 'color': '颜色'}],会根据最小最大值来匹配;可以只最小值或最大值,表示最小值之上,最大值之下
)
map.render('地图.html')
2.中国地图
import json
from pyecharts.charts import Map
from pyecharts.options import TitleOpts, VisualMapOpts

# 获取json文件数据
file_obj = open('E:/资料/Python/资料/可视化案例数据/地图数据/疫情.txt', 'r', encoding='utf-8')
json_data = file_obj.read()
file_obj.close()
# json类型转换为python类型
py_data = json.loads(json_data)
py_data = py_data['areaTree'][0]['children']
# 创建一个空列表用于添加data元组
data_list = []
# for循环会把py_data中的每一个元素赋值给provice,因此利用provice对其下的元素进行直接获取,不用再从py_data下一级的元素来循环获取
for provice in py_data:
    provice_name = provice['name']
    provice_comfirm = provice['total']['confirm']
    # 将元组添加至列表
    data_list.append((provice_name, provice_comfirm))
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': 99, 'label': '1-99人', 'color': '#CCFFFF'},
            {'min': 100, 'max': 999, 'label': '100-999人', 'color': '#FFCCCC'},
            {'min': 1000, 'max': 9999, 'label': '1000-9999人', 'color': '#FF6666'},
            {'min': 10000, 'max': 99999, 'label': '10000-99999人', 'color': '#FF6666'},
            {'min': 100000, 'label': '100000人以上', 'color': '#993333'}
        ]
    )
)
map.render('中国疫情确诊人数地图.html')
3.省级地图
import json
from pyecharts.charts import Map
from pyecharts.options import TitleOpts, VisualMapOpts

file_obj = open('E:/资料/Python/资料/可视化案例数据/地图数据/疫情.txt', 'r', encoding='utf-8')
json_data = file_obj.read()
file_obj.close()
py_data = json.loads(json_data)
py_data = py_data['areaTree'][0]['children'][3]['children']
# 创建空列表
data_list = []
for area in py_data:
    area_name = area['name'] + '市'
    confirm_count = area['total']['confirm']
    data_list.append((area_name, confirm_count))
# 手动添加济源市数据
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': '#CCFFFF'},
            {'min': 10, 'max': 99, 'label': '10-99人', 'color': '#FFCCCC'},
            {'min': 100, 'max': 499, 'label': '100-499人', 'color': '#FF6666'},
            {'min': 500, 'max': 999, 'label': '500-999人', 'color': '#FF6666'},
            {'min': 1000, 'label': '1000人以上', 'color': '#993333'}
        ]
    )
)
map.render('河南省疫情确诊人数地图.html')

5.Pycharts–Bar柱状图

①add_xaxis中的数据为列表

②add_yaxis中的数据也是列表

③可以使用系列配置项中的abel_opts=LabelOpts(position=‘right’)对标签进行设置

④可以使用reversal_axis()将x、y轴翻转

1.基础柱状图
from pyecharts.charts import Bar
from pyecharts.options import LabelOpts

bar = Bar()
bar.add_xaxis(['中国', '美国', '印度'])
# 可以使用系列配置项将lable数据标签在右侧显示
bar.add_yaxis('GDP', [60, 30, 20], label_opts=LabelOpts(position='right'))
# 反转x轴和y轴
bar.reversal_axis()
bar.render('GDP.html')
2.基础时间线柱状图–Tileline
1.时间线设置
# 对时间线进行设置
timeline.add_schema(
    # 自动播放时间间隔:单位毫秒
    play_interval=900,
    # 是否在自动播放的时候显示时间戳:默认True
    is_timeline_show=True,
    # 是否自动播放
    is_auto_play=True,
    # 是否循环播放:默认True
    is_loop_play=True
)
2.时间线主题设置

①该主题是对Timeline设置的而不是Bar,对Bar设置可以用全局配置项,但是Timeline不可以使用全球配置项

步骤:
1.导包
2.传入参数:是一个元组
from pyecharts.globals import ThemeType
timeline = Timeline({'theme': ThemeType.LIGHT})

②主题参数如下

在这里插入图片描述

3.GDP动态图
from pyecharts.charts import Bar, Timeline
from pyecharts.options import LabelOpts
from pyecharts.globals import ThemeType

bar = Bar()
bar.add_xaxis(['中国', '美国', '印度'])
bar.add_yaxis('GDP', [70, 40, 30], label_opts=LabelOpts(position='right'))
bar.reversal_axis()
bar1 = Bar()
bar1.add_xaxis(['中国', '美国', '印度'])
bar1.add_yaxis('GDP', [80, 50, 40], label_opts=LabelOpts(position='right'))
bar1.reversal_axis()
bar2 = Bar()
bar2.add_xaxis(['中国', '美国', '印度'])
bar2.add_yaxis('GDP', [80, 60, 50], label_opts=LabelOpts(position='right'))
bar2.reversal_axis()

timeline = Timeline({'theme': ThemeType.LIGHT})
timeline.add(bar, 'b')
timeline.add(bar1, 'b1')
timeline.add(bar2, 'b2')
# 对时间线进行设置
timeline.add_schema(
    # 自动播放时间间隔:单位毫秒
    play_interval=900,
    # 是否在自动播放的时候显示时间戳:默认True
    is_timeline_show=True,
    # 是否自动播放
    is_auto_play=True,
    # 是否循环播放:默认True
    is_loop_play=True
)
timeline.render('时间线柱状图.html')
3.全球前八GDP柱状图
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType

# 读取文件:csv格式文件利用GB2312的编码
file_obj = open('E:\资料\Python\资料\可视化案例数据\动态柱状图数据/1960-2019全球GDP数据.csv', 'r', encoding='GB2312')
# readlines():返回一个列表,并且可以根据所以访问每一行的数据;使用read()读取到的是字符串
json_data = file_obj.readlines()
# 去掉第一行数据
json_data.pop(0)
# 将数据转换为字典格式{年份:[[国家,gdp],[国家,gdp],...],年份:[[国家,gdp],[国家,gdp],...],...}
dic = {}
# 使用for循环读取列表中每行元素的内容,line为字符串,
for line in json_data:
    # 1960,美国,5.433E+11--使用split用逗号进行分割,并获取年、国家、gdp
    # 通过利用split方法来切割字符转,利用逗号进行分割,分割后下表为0的元素为年份
    year = line.split(',')[0]
    country = line.split(',')[1]
    gdp = float(line.split(',')[2])
    # 将数据按年份存储到字典中
    # 如何判断字典里面有没有指定的key值,如果字典里有对应的年份,直接添加数据,如果没有年份先创建一个该年份的key然后再添加数据
    try:
        # dic[year]表示对应的值,即在本案例中为列表,因此可以使用append进行添加列表数据
        dic[year].append([country, gdp])
    except KeyError:
        dic[year] = []
        dic[year].append([country, gdp])
timeline = Timeline({'theme': ThemeType.LIGHT})
# 为了保证年份是从1960开始并且从小到大来现实的,采取sorted来排序
sorted_data = sorted(dic.keys())
for year in sorted_data:
    # 将字典中年对应的值的列表按照gdp从高到低排序
    dic[year].sort(key=lambda e: e[1], reverse=True)
    # 取出本年的前8名数据
    year_data_dic = dic[year][0:8]
    # 构建两个列表用于表示x轴、y轴
    x_data = []
    y_data = []
    #外面的循环是获取前八名的数据,并添加到两个列表中;下面的for循环是将这八个数据中的国家和gdp添加到两个列表中
    for country_gdp in year_data_dic:
        # x轴添加国家
        x_data.append(country_gdp[0])
        # y轴添加gdp
        y_data.append(country_gdp[1] / 100000000)
    bar = Bar()
    # 将列表翻转,为了保证gdp高的在上,低的在下
    x_data.reverse()
    y_data.reverse()
    bar.add_xaxis(x_data)
    bar.add_yaxis('gpg(亿)', y_data, label_opts=LabelOpts(position='right'))
    bar.reversal_axis()
    bar.set_global_opts(
        title_opts=TitleOpts(title=f'{year}年全球前八GDP')
    )
    timeline.add(bar, str(year))
timeline.add_schema(
    play_interval=100,
    is_timeline_show=True,
    is_loop_play=True,
    is_auto_play=True
)
timeline.render('gdp统计图.html')

将列表翻转,为了保证gdp高的在上,低的在下
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis(‘gpg(亿)’, y_data, label_opts=LabelOpts(position=‘right’))
bar.reversal_axis()
bar.set_global_opts(
title_opts=TitleOpts(title=f’{year}年全球前八GDP’)
)
timeline.add(bar, str(year))
timeline.add_schema(
play_interval=100,
is_timeline_show=True,
is_loop_play=True,
is_auto_play=True
)
timeline.render(‘gdp统计图.html’)


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值