使用的技术:
"""
演示JSON数据和Python字典的相互转换
"""
import json
# 准备列表,列表内每个元素都是字典,转换为JSON字符串
myList = [{"name": "Mike", "age": 15}, {"name": "Tom", "age": 25}, {"name": "Bill", "age": 35}]
json_str1 = json.dumps(myList)
print(json_str1)
print(type(json_str1))
# 准备字典,转换为JSON字符串
myDict = {"name": "Mike", "age": 15}
json_str2 = json.dumps(myDict)
print(json_str2)
print(type(json_str2))
"""
演示JSON数据和Python字典的相互转换
"""
import json
# 讲JSON字符串转换为Python数据类型[{k1: v1, k2: v2}, {k3: v3, k4: v4}]
myStr1 = '[{"name": "Mike", "age": 15}, {"name": "Tom", "age": 25}, {"name": "Bill", "age": 35}]'
js1 = json.loads(myStr1)
print(js1)
print(type(js1))
# 讲JSON字符串转换为Python数据类型{k1: v1, k2: v2}
myStr2 = '{"name": "Mike", "age": 15}'
js2 = json.loads(myStr2)
print(js2)
print(type(js2))
from pyecharts.charts import Line
# 创建一个折线图对象
line = Line()
# 给折线图对象添加x轴的数据
line.add_xaxis(["中国", "美国", "英国"])
# 给折线图对象添加y轴的数据
line.add_yaxis("GDP", [30, 20, 10])
# 通过render方法,将代码生成为图像
line.render()
至此已经得到一个简单折线图,现在进行全局配置,以使之更美观
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts
# 创建一个折线图对象
line = Line()
# 给折线图对象添加x轴的数据
line.add_xaxis(["中国", "美国", "英国"])
# 给折线图对象添加y轴的数据
line.add_yaxis("GDP", [30, 20, 10])
# 设置全局配置项
line.set_global_opts(
# 设置标题
title_opts=TitleOpts(title="GDP展示图", pos_left="center", pos_bottom="1%"),
# 设置图例
legend_opts=LegendOpts(is_show=True),
# 右上角工具箱
toolbox_opts=ToolboxOpts(is_show=True),
# 视觉映射
visualmap_opts=VisualMapOpts(is_show=True)
)
# 通过render方法,将代码生成为图像
line.render()
import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, LabelOpts
# 读取数据
f_us = open("D:\\MyStudy\\MyCode\\PycharmProjects\\py_01\\美国.txt", "r", encoding="UTF-8")
f_jp = open("D:\\MyStudy\\MyCode\\PycharmProjects\\py_01\\日本.txt", "r", encoding="UTF-8")
f_in = open("D:\\MyStudy\\MyCode\\PycharmProjects\\py_01\\印度.txt", "r", encoding="UTF-8")
us_data = f_us.read()
jp_data = f_jp.read()
in_data = f_in.read()
# JSON转Python字典
us_dict = json.loads(us_data)
jp_dict = json.loads(jp_data)
in_dict = json.loads(in_data)
# 获取trend key
us_trend_data = us_dict['data'][0]['trend']
jp_trend_data = jp_dict['data'][0]['trend']
in_trend_data = in_dict['data'][0]['trend']
# 获取日期数据,用于x轴
us_x_data = us_trend_data['updateDate'][:314]
jp_x_data = jp_trend_data['updateDate'][:314]
in_x_data = in_trend_data['updateDate'][:314]
# 获取确认数据,用于Y轴
us_y_data = us_trend_data['list'][0]['data'][:314]
jp_y_data = jp_trend_data['list'][0]['data'][:314]
in_y_data = in_trend_data['list'][0]['data'][:314]
# 设置图表参数
line = Line()
line.add_xaxis(us_x_data)
line.add_yaxis("美国确诊人数", us_y_data, label_opts=LabelOpts(is_show=False))
line.add_yaxis("日本确诊人数", jp_y_data, label_opts=LabelOpts(is_show=False))
line.add_yaxis("印度确诊人数", in_y_data, label_opts=LabelOpts(is_show=False))
# 设置全局配置项
line.set_global_opts(
# 设置标题
title_opts=TitleOpts(title="2020年美日印新冠确诊折线图", pos_left="center", pos_bottom="1%"),
# 设置图例
legend_opts=LegendOpts(is_show=True),
)
line.render()
# 关闭文件对象
f_us.close()
f_jp.close()
f_in.close()
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts
# 准备地图对象
map = Map()
# 准备数据
data = [
("北京市", 5),
("上海市", 8),
("山西省", 50),
("河北省", 80),
("陕西省", 200),
("河南省", 500)
]
# 添加数据
map.add("测试地图", 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": "#FF6666"},
{"min": 100, "max": 500, "label": "100-500", "color": "#990033"}
]
)
)
# 绘图
map.render()
import json
from pyecharts.charts import Map
from pyecharts.options import *
# 读取数据
f = open("D:\\MyStudy\\MyCode\\PycharmProjects\\py_01\\疫情.txt", "r", encoding="UTF-8")
data = f.read()
# 关闭文件
f.close()
# 取到各省的数据
# 将字符串JSON转化为Python字典
data_dict = json.loads(data)
# 组装每个省份和确诊人数为元组,并将各个省的数据封装入列表内
province_data_list = data_dict["areaTree"][0]["children"]
data_list = []
for province_data in province_data_list:
province_name = province_data["name"] + "省" # 省份名称
province_confirm = province_data["total"]["confirm"] # 确诊人数
data_list.append((province_name, province_confirm))
# 创建地图对象
myMap = Map()
# 添加数据
myMap.add("各省份确诊人数", data_list, "china")
# 设置全局变量,定制分段的视觉映射
myMap.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": "#FFFF99"},
{"min": 1000, "max": 4999, "label": "1000-4999人", "color": "#FF9966"},
{"min": 5000, "max": 9999, "label": "5000-9999人", "color": "#FF6666"},
{"min": 10000, "max": 99999, "label": "10000-99999人", "color": "#CC3333"},
{"min": 100000, "label": "100000人以上", "color": "#990033"}
]
)
)
# 绘图
myMap.render("全国疫情地图.html")
PS:因版本原因,省级行政区名与地图不匹配,部分无法显示
import json
from pyecharts.charts import Map
from pyecharts.options import *
# 读取数据
f = open("D:\\MyStudy\\MyCode\\PycharmProjects\\py_01\\疫情.txt", "r", encoding="UTF-8")
data = f.read()
# 关闭文件
f.close()
# 取到山西省的数据
# 将字符串JSON转化为Python字典
data_dict = json.loads(data)
# 组装每个市和确诊人数为元组,并将各个省的数据封装入列表内
city_data_list = data_dict["areaTree"][0]["children"][21]["children"]
data_list = []
for city_data in city_data_list:
city_name = city_data["name"] + "市" # 省份名称
city_confirm = city_data["total"]["confirm"] # 确诊人数
data_list.append((city_name, city_confirm))
# 创建地图对象
myMap = Map()
# 添加数据
myMap.add("山西省确诊人数", data_list, "山西")
# 设置全局变量,定制分段的视觉映射
myMap.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": "#FFFF99"},
{"min": 100, "label": "100人以上", "color": "#990033"}
]
)
)
# 绘图
myMap.render("山西省疫情地图.html")
from pyecharts.charts import Bar
# 使用Bar构建基础柱状图
bar = Bar()
bar.add_xaxis(["CHA", "USA", "UK"])
bar.add_yaxis("GDP", [50, 40, 30], label_opts=LabelOpts(position="right"))
# 反转x轴和y轴
bar.reversal_axis()
bar.render("基础柱状图.html")
from pyecharts.charts import Bar, Timeline
from pyecharts.options import LabelOpts
# 使用Bar构建基础柱状图
bar1 = Bar()
bar1.add_xaxis(["CHA", "USA", "UK"])
bar1.add_yaxis("GDP", [50, 40, 30], label_opts=LabelOpts(position="right"))
bar1.reversal_axis()
bar2 = Bar()
bar2.add_xaxis(["CHA", "USA", "UK"])
bar2.add_yaxis("GDP", [70, 50, 40], label_opts=LabelOpts(position="right"))
bar2.reversal_axis()
bar3 = Bar()
bar3.add_xaxis(["CHA", "USA", "UK"])
bar3.add_yaxis("GDP", [100, 80, 70], label_opts=LabelOpts(position="right"))
bar3.reversal_axis()
# 添加时间线对象
timeLine = Timeline()
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
)
# 绘图
timeLine.render("基础时间线柱状图.html")
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
# 读取数据
f = open("D:\\MyStudy\\MyCode\\PycharmProjects\\py_01\\1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()
# 关闭文件
f.close()
# 删除第一条数据
data_lines.pop(0)
# 将数据转换为字典存储
# 格式:{ 1960: [ ["USA", 123456], ["CHA", 123456] ],
# 1961: [ ["USA", 123456], ["CHA", 123456] ]
# }
data_dict = {}
for line in data_lines:
year = int(line.split(",")[0])
country = line.split(",")[1]
gdp = float(line.split(",")[2])
try:
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])
# 创建时间线对象
timeLine = Timeline()
# 排序年份
sorted_year_list = sorted(data_dict.keys())
# for循环提取每一年的数据
for sorted_year in sorted_year_list:
data_dict[sorted_year].sort(key=lambda element: element[1], reverse=True)
year_data = data_dict[sorted_year][0:8]
x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0])
y_data.append(country_gdp[1] / 100000000) # 按亿为单位
# 反转后插入
x_data.reverse()
y_data.reverse()
# 基于每一年的数据,创建每一年的bar对象
bar = Bar()
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"{sorted_year}年全球GDP前八位")
)
# 在for中,将每一年的bar对象添加到时间线中
timeLine.add(bar, str(sorted_year))
# 设置时间线对象
timeLine.add_schema(
play_interval=1000, # 单位:毫秒
is_timeline_show=True,
is_auto_play=True,
is_loop_play=False
)
# 绘图
timeLine.render("1960-2019全球GDP前八位.html")