学习Python Day6

一、Json

1.Json的定义

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

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

主要功能:Json就是一种在各个编程语言中流通的数据格式,负责再不同编程语言中的数据传递与交互

例如:

Python格式数据->Json格式数据->C语言格式数据

C语言格式数据->Json格式数据-->Python格式数据

2.Json数据格式

Json数据格式可以是字典也可以是嵌套字典的列表

Json就是把Python的字典或嵌套字典的列表转化为字符串

3.Python与Json的相互转化 

例如:

#导入Json模块
import json
#准备一个元素都是字典的列表
data=[{"name":"小明","age":13},{"name":"小张","age":15},{"name":"小红","age":12}]
Json_str=json.dumps(data,ensure_ascii=False)
#ensure_ascii=False使它能展现出中文,若为True则会将汉字用ASCII码转化
print(type(Json_str))
print(Json_str)
s='[{"name":"小明","age":13},{"name":"小张","age":15},{"name":"小红","age":12}]'
l=json.loads(s)
print(type(l))
print(l)

 

由此可知,Json数据是字符串,转化为Python时为列表或字典 

二、pyecharts

如果想要做出可视化数据效果图,则通过pyecharts来实现

1.网站

官网:pyecharts.org

画廊功能网站(可以得到各式各样的图表):gallery.pyecharts.org

2.下载pyecharts模块

在命令提示符中输入pip install pyecharts,回车下载,下载界面如图

 再输入python回车,最后输入import pyecharts,如果正常运行则安装成功

 3.基础折线图

例如:

#导入pyecharts.charts的模块中的Line功能
from pyecharts.charts import Line
line=Line()
#添加x坐标的数据
line.add_xaxis(["小明","小红","小张"])
#添加y坐标的数据
line.add_yaxis("grade",[90,80,70])
#生成折线图
line.render()

运行后会生成一个.html文件

点击文件然后选择右上角的浏览器即可阅览图像

 4.全局配置

配置方法:set_global_opts方法

title_opts:配置标题

 legend_opts:配置图例

toolbox_opts:配置工具箱

visualmap_opts:配置视觉映射

PS:可以通过官网pyecharts.org查看全局配置项

 使用图中这些Opts的功能时,需要导入options模块

即加入from pyecharts.options import 功能名

例如: from pyecharts.options import Titleopts

#导入pyecharts.charts的模块中的Line功能
from pyecharts.charts import Line
#导入pyecharts.options的模块中的功能
from pyecharts.options import TitleOpts
line=Line()
#添加x坐标的数据
line.add_xaxis(["小明","小红","小张"])
#添加y坐标的数据
line.add_yaxis("grade",[90,80,70])
#全局配置配上标题
line.set_global_opts(
    title_opts=TitleOpts(title="成绩展示",pos_left="center",pos_bottom="1%")
#pos_left表示到左边的距离,pos_bottom表示到底部的距离
)
#生成折线图
line.render()

 

5.数据处理

数据文件来源于黑马程序员资料中的"美国.txt"

下载指南:

https://www.bilibili.com/read/cv11763184

#导包
import json
#打开文件
f_us=open("E:/美国.txt","r",encoding="UTF-8")
#读取全部内容
us_data=f_us.read()
#删去不符合json格式的字符
us_data=us_data.replace("jsonp_1629344292311_69436(","")
us_data=us_data[:-2]
#将json格式转化为python语言格式
us_dirt=json.loads(us_data)
#拿出data里的trend数据
trend_data=us_dirt["data"][0]["trend"]
#将前313天的数据调出,时间为x坐标,确诊人数为y坐标
x_data=trend_data["updateDate"][:314]
y_data=trend_data["list"][0]["data"][:314]
print(x_data)
print(y_data)

最终便可得到两个坐标的数据

6、生成折线图

代码如下:

#导包
import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts,LabelOpts
#打开文件
f_us=open("E:/美国.txt","r",encoding="UTF-8")
#读取全部内容
us_data=f_us.read()
#删去不符合json格式的字符
us_data=us_data.replace("jsonp_1629344292311_69436(","")
us_data=us_data[:-2]
#将json格式转化为python语言格式
us_dirt=json.loads(us_data)
#拿出data里的trend数据
trend_data=us_dirt["data"][0]["trend"]
#将前313天的数据调出,时间为x坐标,确诊人数为y坐标
x_data=trend_data["updateDate"][:314]
y_data=trend_data["list"][0]["data"][:314]
#生成图表
line=Line()
line.add_xaxis(x_data)
line.add_yaxis("美国确诊人数",y_data,label_opts=LabelOpts(is_show=False))#使曲线不会显现数据
line.set_global_opts(
    title_opts=TitleOpts(title="美国确诊人数增长情况",pos_left="center",pos_bottom="1%")
)
line.render()
f_us.close()

 折线图如下:

 三、构建全国地图可视化图表

与折线图不同的是:地图的导包是导from pyecharts.cherts import Map

添加数据到地图中:map.add("名称",数据,"地图类型")

下面完成中国疫情地图的绘制

#导包
import json
from pyecharts.charts import Map
from pyecharts.options import *
from pyecharts.options import VisualMapOpts
#读取数据文件
f=open("E:/疫情.txt","r",encoding="UTF-8")
data=f.read()
#将json格式转化为python格式
data_dirt=json.loads(data)
province_data_list=data_dirt["areaTree"][0]["children"]
data_list=[]#用来存放省份名称及对应的确诊人数
for province_data in province_data_list:
    #获取省份名称
    name=province_data["name"]
    #获取确诊人数
    confirm=province_data["total"]["confirm"]
    data_list.append((name,confirm))
print(data_list)
map=Map()
map.add("各省确诊人数",data_list,"china")#将数据导入地图
map.set_global_opts(
    title_opts=TitleOpts("全国疫情地图",pos_left="center",pos_bottom="1%"),
    visualmap_opts=VisualMapOpts(
        is_show=True,
        is_piecewise=True,  # 使我们可以自己设置校准范围
        pieces=[
            {"min": 1, "max": 99, "label": "1-99", "color": "#58a8f9"},
            {"min": 100, "max": 999, "label": "100-999", "color": "#51fb55"},
            {"min": 1000, "max": 4999, "label": "1000-4999", "color": "#cffb51"},
            {"min": 5000, "max": 9999, "label": "5000-9999", "color": "#fbf951"},
            {"min": 10000, "max": 19999, "label": "10000-19999", "color": "#fbc351"},
            {"min": 20000,  "label": "20000+", "color": "#fb6651"},
        ]  # 配置每个区间显示的颜色
    )
)
map.render()
f.close()


 四、基础柱状图

1.柱状图的绘制

通过bar来构建柱状图

导包:from pyecharts.charts import Bar

反转x,y轴:bar.reveral_axis

示例:

#导包
from pyecharts.charts import Bar
from pyecharts.options import LabelOpts
bar=Bar()
#导入x数据
bar.add_xaxis(["中国","美国","英国"])
#导入y数据
bar.add_yaxis("GDP",[30,20,10],label_opts=LabelOpts(position="right"))
#反转x和y轴
bar.reversal_axis()
#绘图
bar.render()

 其中position="right"表示将数字标签标到右边

2.时间柱状图

(1)timeline( )时间线

如果说一个Bar,Line是一个图表对象,时间线就是创建一个一维的x轴,轴上每个点为一个图表对象。

#导包
from pyecharts.charts import Bar,Timeline
from pyecharts.options import LabelOpts
bar1=Bar()
bar1.add_xaxis(["中国","美国","英国"])
bar1.add_yaxis("GDP",[10,20,50],label_opts=LabelOpts(position="right"))
bar1.reversal_axis()
bar2=Bar()
bar2.add_xaxis(["中国","美国","英国"])
bar2.add_yaxis("GDP",[70,80,70],label_opts=LabelOpts(position="right"))
bar2.reversal_axis()
bar3=Bar()
bar3.add_xaxis(["中国","美国","英国"])
bar3.add_yaxis("GDP",[150,140,90],label_opts=LabelOpts(position="right"))
bar3.reversal_axis()
#绘图
timeline=Timeline()
timeline.add(bar1,"点1")
timeline.add(bar2,"点2")
timeline.add(bar3,"点3")
timeline.render()

(2) 自动播放的语法:

(3) 时间线设置主题:

语法:from pyecharts.globals import ThemeType

timeline=Timeline(

{"theme":ThemeType.主题类型}

 

五、GDP动态柱状图

1,列表的sort方法

 2.制作GDP动态柱状图

文件来自黑马资料"1960-2019各国GDP"

#导包
from pyecharts.charts import Bar,Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
#读取文件
f=open("E:/1960-2019全球GDP数据.csv","r",encoding="GB2312")
data_lines=f.readlines()
#关闭文件
f.close()
#删除第一条数据
data_lines.pop(0)
data_dict={}
for line in data_lines:
    #用逗号作为分割的符号,得到年份,国家,GDP
    year=int(line.split(",")[0])
    country=line.split(",")[1]
    gdp=float(line.split(",")[2])#讲科学计数法转化为具体数字(float)
    try:
        data_dict[year].append([country,gdp])
    except KeyError:
        data_dict[year]=[]
        data_dict[year].append([country, gdp])
print(data_dict)
#创建时间线对象
timeline=Timeline({"theme":ThemeType.LIGHT})
#排序年份
sorted_year_list=sorted(data_dict.keys())
for year in sorted_year_list:
    #以列表第2个元素即GDP作为排序依据
    data_dict[year].sort(key=lambda element:element[1],reverse=True)
    year_data=data_dict[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)
    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}年前8GDP")
    )
    timeline.add(bar,str(year))
#设置自动播放
timeline.add_schema(
    play_interval=100,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=False
)
timeline.render()

 今天先到这里,明天开始对象部分

共勉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值