JSON

json简介

JSON是一种轻量级的数据交换格式。采用完全独立于编程语言的文本格式来存储和表示数据。
JSON本质上是一个带有特定格式的字符串。
JSON就是一种在各个编程语言中流通的数据格式,负责不同编程语言中的数据传递和交互。

1
2
3
4
5
6
//JSON对象
{"name":"admin","age":18}
//JSON数组
[{"name":"admin","age":18},{"name":"root","age":16},{"name":"张三","age":20}]
//组合使用
{"sites":[{"name":"A","url":"A.com"},{"name":"B","url":"B.com"}]}

json格式数据转化

使用JSON函数需要导入 json 库:import json

1
2
3
4
5
6
7
8
9
10
11
12
# 导入json模块 
import json

# 准备符合格式json格式要求的python数据
data = [{"name": "张三", "age": 23}, {"name": "李四", "age": 24}]

# 通过json.dumps(data)方法将python数据转化为json数据
# 中文可以使用ensure_ascii=False参数来确保中文正常转换
data = json.dumps(data, ensure_ascii=False)

# 通过json.loads(data)方法把josn数据转化为python列表或字典
data = json.loads(data)

pyecharts模块介绍

Echarts是由百度开源的数据可视化图表库。

pyecharts是一款将python与echarts结合的强大的数据可视化工具。

使用pyecharts可以生成独立的网页。

可使用pip安装pyecharts模块,语法如下:pip install pyecharts


pyecharts快速入门

pyecharts模块配置选项

pyecharts模块中有很多的配置选项, 常用到2个类别的选项:

  • 全局配置选项
  • 系列配置选项

全局配置项可配置图表的标题、配置图例、配置鼠标移动效果、配置工具栏等整体配置项。
全局配置选项可以通过set_global_opts方法来进行配置,相应的选项和选项的功能如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 导包,导入Line功能构建折线图对象
from pyecharts.charts import Line
#导包,导入全局配置组件
from pyecharts.options import *

# 得到折线图对象
line = Line()
# 全局配置选项
line.set_global_opts(
title_opts=TitleOpts(title="天气",pos_left='center',pos_bottom='1%'),
legend_opts=LegendOpts(is_show=True),
toolbox_opts=ToolboxOpts(is_show=True),
visualmap_opts=VisualMapOpts(is_show=True),
tooltip_opts=TitleOpts(is_show=True)
)
# 添加x轴数据
line.add_xaxis(["第一天", "第二天", "第三天"])
# 添加y轴数据
line.add_yaxis("气温", [23, 33, 11])
line.add_yaxis("湿度", [60, 33, 22])
# 生成图表
line.render()

折线图可视化

基础折线图

1
2
3
4
5
6
7
8
9
10
11
# 导包,导入Line功能构建折线图对象
from pyecharts.charts import Line

# 得到折线图对象
line = Line()
# 添加x轴数据
line.add_xaxis(["第一天", "第二天", "第三天"])
# 添加y轴数据
line.add_yaxis("气温", [23, 33, 11])
# 生成图表
line.render()

地图可视化

全国地图可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 导包,导入Map功能构建地图对象和配置组件
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts

# 得到地图对象
map = Map()
# 准备数据
province = ["北京市","上海市","广东省"]
value = [987,654,321]
data = list(zip(province,value)) # 打包为一个个元组的列表 [("北京市", 987),("上海市", 654),("广东省", 321)]
# 添加数据
map.add("中国地图", data, "china")

# 设置全局选项
map.set_global_opts(
visualmap_opts=VisualMapOpts(
is_show=True, # 是否显示视觉映射配置(左下角)
is_piecewise=True, # 是否分段
pieces=[ # 自定义的每一段的范围
{"min": 1, "max": 333, "label": "1-333", "color": "#0000FF"},
{"min": 334, "max": 666, "label": "334-666", "color": "#00FF00"},
{"min": 667, "max": 999, "label": "667-999", "color": "#FF0000"}
]
)
)


# 绘图
map.render("全国地图.html")

省级地图可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 导包,导入Map功能构建地图对象和配置组件
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts

# 准备地图对象
map = Map()
# 准备数据
city = ["西安市","宝鸡市","榆林市"]
value = [1,11,111]
data = [list(z) for z in zip(city,value)]
print(data) # [['西安市', 1], ['宝鸡市', 11], ['榆林市', 111]]
# 添加数据
map.add("陕西地图", data, "陕西")

# 设置全局选项
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": "#FF6666"},
{"min": 100, "max": 500, "label": "100-500", "color": "#990033"}
]
)
)

# 绘图
map.render("陕西地图.html")

市级地图可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 导包,导入Map功能构建地图对象和配置组件
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts

# 准备地图对象
map = Map()
# 准备数据
data = [
("榆阳区", 99),
("靖边县", 199),
("定边县", 299)
]
# 添加数据
map.add("榆林地图", data, "榆林")

# 设置全局选项
map.set_global_opts(
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True,
pieces=[
{"min": 1, "max": 99, "label": "1-99", "color": "#CCFFFF"},
{"min": 100, "max": 199, "label": "100-199", "color": "#FF6666"},
{"min": 200, "max": 500, "label": "200-500", "color": "#990033"}
]
)
)

# 绘图
map.render("榆林地图.html")

动态柱状图

基础柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
# 导包,导入Bar功能构建柱状图对象和配置组件
from pyecharts.charts import Bar
from pyecharts import options as opts
# 使用Bar构建基础柱状图
bar = Bar()
# 添加x轴的数据
bar.add_xaxis(["中国", "美国", "英国"])
# 添加y轴数据,设置数值标签在右侧
bar.add_yaxis("GDP", [30, 20, 10], label_opts=opts.LabelOpts(position="right"))
# 反转x和y轴
bar.reversal_axis()
# 绘图
bar.render("基础柱状图.html")

基础时间线柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 导包,导入Bar功能构建柱状图对象和配置组件
from pyecharts.charts import Bar, Timeline
from pyecharts.options import LabelOpts
from pyecharts.globals import ThemeType

bar1 = Bar()
bar1.add_xaxis(["中国", "美国", "英国"])
bar1.add_yaxis("GDP", [30, 20, 10], label_opts=LabelOpts(position="right"))
bar1.reversal_axis()

bar2 = Bar()
bar2.add_xaxis(["中国", "美国", "英国"])
bar2.add_yaxis("GDP", [50, 40, 30], label_opts=LabelOpts(position="right"))
bar2.reversal_axis()

bar3 = Bar()
bar3.add_xaxis(["中国", "美国", "英国"])
bar3.add_yaxis("GDP", [70, 60, 60], label_opts=LabelOpts(position="right"))
bar3.reversal_axis()

# 构建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
# 在时间线内添加柱状图对象
timeline.add(bar1, "时间点1")
timeline.add(bar2, "时间点2")
timeline.add(bar3, "时间点3")

# 自动播放设置
timeline.add_schema(
play_interval=1000, # 自动播放时间间隔,单位毫秒
is_timeline_show=True, # 自动播放时,是否显示时间线
is_auto_play=True, # 是否自动播放
is_loop_play=True # 是否自动循环
)

# 用时间线对象绘图,而不是bar对象
timeline.render("基础时间线柱状图.html")

GDP动态柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType

# 数据
data_lines = [
'1960,美国,5.43E+11', '1960,英国,73233967692', '1960,法国,62225478000', '1960,中国,59716467625',
'1961,美国,5.63E+11', '1961,中国,50056868957', '1961,英国,7.77E+10', '1961,法国,6.75E+10',
'1962,美国,6.05E+11', '1962,中国,6.72E+10', '1962,英国,8.12E+10', '1962,印度,42161481858',
'1963,美国,6.39E+11', '1963,中国,5.07E+10', '1963,英国,8.66E+10', '1963,法国,8.48E+10',
]
# 将数据转换为字典存储,格式为:
# { 年份: [ [国家, gdp], [国家,gdp], ...... ], 年份: [ [国家, gdp], [国家,gdp], ...... ], ...... }
# 定义字典对象
data_dict = {}
for line in data_lines:
year = int(line.split(",")[0]) # 年份
country = line.split(",")[1] # 国家
gdp = float(line.split(",")[2]) # gdp数据
# 判断字典里是否存在指定的key
try:
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])

# 创建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
# 排序年份
sorted_year_list = sorted(data_dict.keys())
for year in sorted_year_list:
data_dict[year].sort(key=lambda element: element[1], reverse=True) # 按照GDP降序
# 取出本年份前3名的国家
year_data = data_dict[year][0:3]

x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0]) # x轴添加国家
y_data.append(country_gdp[1] / 100000000) # y轴添加gdp数据,单位:亿

# 构建柱状图
bar = Bar()
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis("GDP(亿)", y_data, label_opts=LabelOpts(position="right"))
# 反转x轴和y轴
bar.reversal_axis()
# 设置每一年的图表的标题
bar.set_global_opts(
title_opts=TitleOpts(title=f"{year}年全球前3国家GDP数据")
)
timeline.add(bar, str(year))

# 设置时间线自动播放
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=True
)
# 绘图
timeline.render("1960-1963全球GDP前3国家.html")