数据可视化
可视化效果一:2020年印美日新冠累计确诊人数
2020年是新冠疫情爆发的一年,随着疫情的爆发,国内外确诊人数成了大家关心的热点,相信大家都有看过类似的疫情报告.本案例对印度美国日本三个国家确诊人数的进行了可视化处理,形成了可视化的疫情确诊人数报告.
可视化效果二:全国疫情地图可视化
可视化效果三:动态GDP增长图
此处没有办法进行动态变化,希望大家自行想象,接下来开始可视化的学习。
1.json数据转换
JSON是一种轻量级的数据交互格式,可以按照JSON指定的格式去组织和封装数据
JSON本质上是一种带有特定格式的字符串
主要功能:json就是一种在各个编程语言中流通的数据格式,负责不同编程语言中的数据传递和交互 类似于:国际通用语言-英语,中国56个民族不同地区的通用语言-普通话
各种编程语言存储数据的容器不尽相同,在Python中有字典dict这样的数据类型,而其它语言可能没有对应的字典
为了让不同的语言都能够相互通用的互相传递数据,JSON就是一种非常良好的中转数据格式。
json格式数据转化
#json数据的格式可以是:{"name":"admin","age":18}# 也可以是:[{"name":"admin","age":18},{"name":"root","age":16},{"name":"张三","age":20}]
json格式说白了就是python的列表或者字典,唯一的要求就是列表内部嵌套的必须是字典,二对于字典本身的话,就没有任何格式或者形式上的要求。
json本质上是字符串。
Python数据和Json数据之间的相互转化
通过代码来对该知识点进行熟悉
列表嵌套字典形式:
# 导入json模块import json# 准备符合格式json格式要求的python数据data1 = [{"name":"William","age":18},{"name":"Jeff","age":18}]data2 = [{"name":"张三","age":18},{"name":"李四","age":18}]json_str1 = json.dumps(data1)print(type(json_str1))print(json_str1)json_str2 = json.dumps(data2,ensure_ascii=False)print(type(json_str2))print(json_str2)
如果包含中文,那么要加上ensure_ascii=False
字典形式:
import json# 准备字典,将字典转换为Jsond = {"name":"张三","address":"浙江"}json_str = json.dumps(d,ensure_ascii=False)print(type(json_str))print(json_str)# 将python字符串转换为Python数据类型[{k:v,k:v},{k:v,k:v}]s = '[{"name":"张三","address":"浙江"},{"name":"李四","address":"江苏"}]'l = json.loads(s)print(type(l))print(l)
2.pyecharts模块介绍
概况:
Echarts是个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而Python是门富有表达力的语言,很适合用于数据处理.当数据分析遇上数据可视化时pyecharts诞生了。
打开官方网站pyecharts.org
然后打开一个画廊的功能网站 Document
pyecharts模块安装
使用在前面学过的pip命令即可快速安装PyEcharts模块
打开命令提示符,再输入pip install pyecharts
然后输入python,再导入import pyecharts
显示到这里,说明安装没有错误,可以正常使用。
3.pyecharts快速入门
1.基础折线图
# 导包,导入Line功能构建折线图对象from pyecharts.charts import Line# 得到折线图对象line = Line()# 添加x轴数据line.add_xaxis(["中国","美国","英国"])# 添加y轴数据line.add_yaxis("GDP",[30,20,10])# 生成图表line.render()
构建完成我们的折线图之后进行运行操作,会发现旁边文件栏中出现了render.html,点击该文件的网页功能就可以查看相应的网页功能。
2.pyecharts的配置选项
全局配置选项:
set_global_opts方法:
这里全局配置选项可以通过set_global_opts方法来进行配置,相应的选项和选项的功能如下:
当我们完成了图表后,就可以通过set_global_opts方法
Line.set_global_opts(title_opts=TitleOpts("测试",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=TooltipOpts(is_show=True), )
在我们上面原有的基础上进行如下操作:
配置图表的标题
配置图例
配置鼠标移动效果
配置工具栏
等整体配置项
# 导包,导入Line功能构建折线图对象from pyecharts.charts import Line# 得到折线图对象line = Line()# 添加x轴数据line.add_xaxis(["中国","美国","英国"])# 添加y轴数据line.add_yaxis("GDP",[30,20,10])# 设置全局配置项line.set_global_opts(title_)# 生成图表line.render()
在进行查看就会发现这个全局配置出来的可视化图相当不错啦,当然要对这个图进一步改善,引入更多的全局配置内容,那么就需要通过pyecharts的官网了解啦。
3.数据处理
打开一个网站ab173,这是一个懒人工具网站。在里面找到Json视图,然后可以把你选中的数据存放到如下的格式化处理器中,点击校验或者回车操作,这时候可以通过点击视图,将一大串的内容整合成相应的字典、列表包形式。
很多需要的数据都可以通过第三方网站进行展示和模拟。
打开pycharm,进行相应的编码:
import jsonfrom pyecharts.charts import Linefrom pyecharts.options import TitleOpts# 处理数据f_us = open("D:/美国.txt",'r',encoding="UTF-8")us_data = f_us.read() # 获得文件美国的全部内容# 去掉不合JSON规范的开头us_data = us_data.replcae("jsonp_1629344292311_69436(", ")# 去掉不合JSON规范的结尾us_data = us_data[:-2]# JSON转Python字典us_dict = json.loads(us_data)print(type(us_dict))print(us_dict)# 获取trend keytrend_data = us_dict['data'][0]['trend']# 获取日期数据,用于x轴,取2020年(到315下表结束)x_data = json.loads['updateDate'][:314]# 获取确认数据,用于y轴,去2020年(到315下标结束)y_data = trend_data['list'][0]['data']# 生成图表line = line()# 添加x轴数据line.add_xaxis(us_x_data) # 使用一个国家的数据即可# 添加y轴数据line.add_yaxis('美国确诊人数',us_y_data,label_opts=LabelOpts)# 设置全局设置line.set_global_opts(# 标题设置title_opts = TitleOpts(title='2020年美国确诊人数折线图',pos_left='center',pos_bottom='1%'))# 生成图表line.render()# 关闭文件f.close()
再打开json视图,将我们简化过的内容放置于该网站的Json视图中即可,可以查看
遗憾的是我这边暂时没有相应的数据文件和内容,没有办法在网页上对该可视化图进行显示。
可视化案例
1.地图-基础地图使用
基本地图演示:
from pyecharts.charts import Mapfrom pyecharts.options import VisualMapOptsmap = Map()data = [ ("浙江",9), ("江苏",19), ("北京",99), ("上海",199), ("海南",299), ("台湾",199), ("安徽",299), ("广州",399), ("湖北",599),]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": 600, "label": "100-600", "color": "#990033"} ] ))# 绘图map.render()
通过ab173网站,在其中的前端中找到rgb颜色对照表
2.全国疫情地图构建
虽然没有相应的数据,但是不妨碍我们对代码进行熟悉和操作,让我们打开pychart
"""演示全国疫情可视化地图开发"""import jsonfrom pyecharts.charts import Mapfrom pyecharts.options import *# 读取文件f = open("D:/疫情.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"]# 组装每个省份和确诊人数为元组,并各省的数据都封装入列表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)print(data_list)# 创建地图map = Map()# 添加数据map.add("各省份确诊人数",data_list,"china")# 设置全局配置,定制分段的视觉映射map.set_global_opts{title_opts=TitleOpts(title="全国疫情地图"),visualmap_opts=VisualMapOpts(is_show=True,is_piecewise=True,pieces=[ {"min":1,"max":99,"lable":"1~99人","color":"#CCFFFF"}, {"min":100,"max":999,"lable":"100~999人","color":"#FFFF99"}, {"min":1000,"max":4999,"lable":"1000~4999人","color":"#FF9966"}, {"min":5000,"max":9999,"lable":"5000~9999人","color":"#FF6666"}, {"min":10000,"max":99999,"lable":"10000~99999人","color":"#CC3333"}, {"min":100000,"lable":"100000+人","color":"#990033"} ] ),}# 绘图map.render()
3.浙江省空气质量地图绘制
import jsonfrom pyecharts.charts import Mapfrom pyecharts.options import *#f = open("D:/空气质量.txt","r",encording="UTF-8")#data = f.read()#f.close()#data_dict = json.loads(data)#cities_data = data_dict["areaTree"][3]["children"]data_list = []#for city_data in cities_data:#city_name = city_data["name"]+"市"#city_confirm = city_data["total"]["confirm"]#data_list(city_name,city_confirm)#print(data_list)data_list.append(("杭州",12))data_list.append(("湖州",13))data_list.append(("宁波",15))data_list.append(("温州",18))data_list.append(("嘉兴",20))data_list.append(("丽水",34))data_list.append(("台州",56))data_list.append(("衢州",53))data_list.append(("绍兴",18))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":15,"lable":"优秀","color":"#CCFFFF"}, {"min": 16, "max": 30, "lable": "良好", "color": "#FFFF99"}, {"min": 31, "max": 45, "lable": "一般", "color": "#CC9966"}, {"min": 46, "max": 60, "lable": "较差", "color": "#FF6666"}, {"min": 61, "max": 75, "lable": "优秀", "color": "#CC3333"} ] ))map.render("浙江省空气质量监测.html")
4.模仿百度空气可视化
下面是百度的空气质量可视化图:
import pyecharts.options as optsfrom pyecharts.charts import BMapdata = [ ["海门", 9], ["鄂尔多斯", 12], ["招远", 12], ["舟山", 12], ["齐齐哈尔", 14], ["盐城", 15], ["赤峰", 16], ["青岛", 18], ["乳山", 18], ["金昌", 19], ["泉州", 21], ["莱西", 21], ["日照", 21], ["胶南", 22], ["南通", 23], ["拉萨", 24], ["云浮", 24], ["梅州", 25], ["文登", 25], ["上海", 25], ["攀枝花", 25], ["威海", 25], ["承德", 25], ["厦门", 26], ["汕尾", 26], ["潮州", 26], ["丹东", 27], ["太仓", 27], ["曲靖", 27], ["烟台", 28], ["福州", 29], ["瓦房店", 30], ["即墨", 30], ["抚顺", 31], ["玉溪", 31], ["张家口", 31], ["阳泉", 31], ["莱州", 32], ["湖州", 32], ["汕头", 32], ["昆山", 33], ["宁波", 33], ["湛江", 33], ["揭阳", 34], ["荣成", 34], ["连云港", 35], ["葫芦岛", 35], ["常熟", 36], ["东莞", 36], ["河源", 36], ["淮安", 36], ["泰州", 36], ["南宁", 37], ["营口", 37], ["惠州", 37], ["江阴", 37], ["蓬莱", 37], ["韶关", 38], ["嘉峪关", 38], ["广州", 38], ["延安", 38], ["太原", 39], ["清远", 39], ["中山", 39], ["昆明", 39], ["寿光", 40], ["盘锦", 40], ["长治", 41], ["深圳", 41], ["珠海", 42], ["宿迁", 43], ["咸阳", 43], ["铜川", 44], ["平度", 44], ["佛山", 44], ["海口", 44], ["江门", 45], ["章丘", 45], ["肇庆", 46], ["大连", 47], ["临汾", 47], ["吴江", 47], ["石嘴山", 49], ["沈阳", 50], ["苏州", 50], ["茂名", 50], ["嘉兴", 51], ["长春", 51], ["胶州", 52], ["银川", 52], ["张家港", 52], ["三门峡", 53], ["锦州", 54], ["南昌", 54], ["柳州", 54], ["三亚", 54], ["自贡", 56], ["吉林", 56], ["阳江", 57], ["泸州", 57], ["西宁", 57], ["宜宾", 58], ["呼和浩特", 58], ["成都", 58], ["大同", 58], ["镇江", 59], ["桂林", 59], ["张家界", 59], ["宜兴", 59], ["北海", 60], ["西安", 61], ["金坛", 62], ["东营", 62], ["牡丹江", 63], ["遵义", 63], ["绍兴", 63], ["扬州", 64], ["常州", 64], ["潍坊", 65], ["重庆", 66], ["台州", 67], ["南京", 67], ["滨州", 70], ["贵阳", 71], ["无锡", 71], ["本溪", 71], ["克拉玛依", 72], ["渭南", 72], ["马鞍山", 72], ["宝鸡", 72], ["焦作", 75], ["句容", 75], ["北京", 79], ["徐州", 79], ["衡水", 80], ["包头", 80], ["绵阳", 80], ["乌鲁木齐", 84], ["枣庄", 84], ["杭州", 84], ["淄博", 85], ["鞍山", 86], ["溧阳", 86], ["库尔勒", 86], ["安阳", 90], ["开封", 90], ["济南", 92], ["德阳", 93], ["温州", 95], ["九江", 96], ["邯郸", 98], ["临安", 99], ["兰州", 99], ["沧州", 100], ["临沂", 103], ["南充", 104], ["天津", 105], ["富阳", 106], ["泰安", 112], ["诸暨", 112], ["郑州", 113], ["哈尔滨", 114], ["聊城", 116], ["芜湖", 117], ["唐山", 119], ["平顶山", 119], ["邢台", 119], ["德州", 120], ["济宁", 120], ["荆州", 127], ["宜昌", 130], ["义乌", 132], ["丽水", 133], ["洛阳", 134], ["秦皇岛", 136], ["株洲", 143], ["石家庄", 147], ["莱芜", 148], ["常德", 152], ["保定", 153], ["湘潭", 154], ["金华", 157], ["岳阳", 169], ["长沙", 175], ["衢州", 177], ["廊坊", 193], ["菏泽", 194], ["合肥", 229], ["武汉", 273], ["大庆", 279],]geoCoordMap = {"海门": [121.15, 31.89],"鄂尔多斯": [109.781327, 39.608266],"招远": [120.38, 37.35],"舟山": [122.207216, 29.985295],"齐齐哈尔": [123.97, 47.33],"盐城": [120.13, 33.38],"赤峰": [118.87, 42.28],"青岛": [120.33, 36.07],"乳山": [121.52, 36.89],"金昌": [102.188043, 38.520089],"泉州": [118.58, 24.93],"莱西": [120.53, 36.86],"日照": [119.46, 35.42],"胶南": [119.97, 35.88],"南通": [121.05, 32.08],"拉萨": [91.11, 29.97],"云浮": [112.02, 22.93],"梅州": [116.1, 24.55],"文登": [122.05, 37.2],"上海": [121.48, 31.22],"攀枝花": [101.718637, 26.582347],"威海": [122.1, 37.5],"承德": [117.93, 40.97],"厦门": [118.1, 24.46],"汕尾": [115.375279, 22.786211],"潮州": [116.63, 23.68],"丹东": [124.37, 40.13],"太仓": [121.1, 31.45],"曲靖": [103.79, 25.51],"烟台": [121.39, 37.52],"福州": [119.3, 26.08],"瓦房店": [121.979603, 39.627114],"即墨": [120.45, 36.38],"抚顺": [123.97, 41.97],"玉溪": [102.52, 24.35],"张家口": [114.87, 40.82],"阳泉": [113.57, 37.85],"莱州": [119.942327, 37.177017],"湖州": [120.1, 30.86],"汕头": [116.69, 23.39],"昆山": [120.95, 31.39],"宁波": [121.56, 29.86],"湛江": [110.359377, 21.270708],"揭阳": [116.35, 23.55],"荣成": [122.41, 37.16],"连云港": [119.16, 34.59],"葫芦岛": [120.836932, 40.711052],"常熟": [120.74, 31.64],"东莞": [113.75, 23.04],"河源": [114.68, 23.73],"淮安": [119.15, 33.5],"泰州": [119.9, 32.49],"南宁": [108.33, 22.84],"营口": [122.18, 40.65],"惠州": [114.4, 23.09],"江阴": [120.26, 31.91],"蓬莱": [120.75, 37.8],"韶关": [113.62, 24.84],"嘉峪关": [98.289152, 39.77313],"广州": [113.23, 23.16],"延安": [109.47, 36.6],"太原": [112.53, 37.87],"清远": [113.01, 23.7],"中山": [113.38, 22.52],"昆明": [102.73, 25.04],"寿光": [118.73, 36.86],"盘锦": [122.070714, 41.119997],"长治": [113.08, 36.18],"深圳": [114.07, 22.62],"珠海": [113.52, 22.3],"宿迁": [118.3, 33.96],"咸阳": [108.72, 34.36],"铜川": [109.11, 35.09],"平度": [119.97, 36.77],"佛山": [113.11, 23.05],"海口": [110.35, 20.02],"江门": [113.06, 22.61],"章丘": [117.53, 36.72],"肇庆": [112.44, 23.05],"大连": [121.62, 38.92],"临汾": [111.5, 36.08],"吴江": [120.63, 31.16],"石嘴山": [106.39, 39.04],"沈阳": [123.38, 41.8],"苏州": [120.62, 31.32],"茂名": [110.88, 21.68],"嘉兴": [120.76, 30.77],"长春": [125.35, 43.88],"胶州": [120.03336, 36.264622],"银川": [106.27, 38.47],"张家港": [120.555821, 31.875428],"三门峡": [111.19, 34.76],"锦州": [121.15, 41.13],"南昌": [115.89, 28.68],"柳州": [109.4, 24.33],"三亚": [109.511909, 18.252847],"自贡": [104.778442, 29.33903],"吉林": [126.57, 43.87],"阳江": [111.95, 21.85],"泸州": [105.39, 28.91],"西宁": [101.74, 36.56],"宜宾": [104.56, 29.77],"呼和浩特": [111.65, 40.82],"成都": [104.06, 30.67],"大同": [113.3, 40.12],"镇江": [119.44, 32.2],"桂林": [110.28, 25.29],"张家界": [110.479191, 29.117096],"宜兴": [119.82, 31.36],"北海": [109.12, 21.49],"西安": [108.95, 34.27],"金坛": [119.56, 31.74],"东营": [118.49, 37.46],"牡丹江": [129.58, 44.6],"遵义": [106.9, 27.7],"绍兴": [120.58, 30.01],"扬州": [119.42, 32.39],"常州": [119.95, 31.79],"潍坊": [119.1, 36.62],"重庆": [106.54, 29.59],"台州": [121.420757, 28.656386],"南京": [118.78, 32.04],"滨州": [118.03, 37.36],"贵阳": [106.71, 26.57],"无锡": [120.29, 31.59],"本溪": [123.73, 41.3],"克拉玛依": [84.77, 45.59],"渭南": [109.5, 34.52],"马鞍山": [118.48, 31.56],"宝鸡": [107.15, 34.38],"焦作": [113.21, 35.24],"句容": [119.16, 31.95],"北京": [116.46, 39.92],"徐州": [117.2, 34.26],"衡水": [115.72, 37.72],"包头": [110, 40.58],"绵阳": [104.73, 31.48],"乌鲁木齐": [87.68, 43.77],"枣庄": [117.57, 34.86],"杭州": [120.19, 30.26],"淄博": [118.05, 36.78],"鞍山": [122.85, 41.12],"溧阳": [119.48, 31.43],"库尔勒": [86.06, 41.68],"安阳": [114.35, 36.1],"开封": [114.35, 34.79],"济南": [117, 36.65],"德阳": [104.37, 31.13],"温州": [120.65, 28.01],"九江": [115.97, 29.71],"邯郸": [114.47, 36.6],"临安": [119.72, 30.23],"兰州": [103.73, 36.03],"沧州": [116.83, 38.33],"临沂": [118.35, 35.05],"南充": [106.110698, 30.837793],"天津": [117.2, 39.13],"富阳": [119.95, 30.07],"泰安": [117.13, 36.18],"诸暨": [120.23, 29.71],"郑州": [113.65, 34.76],"哈尔滨": [126.63, 45.75],"聊城": [115.97, 36.45],"芜湖": [118.38, 31.33],"唐山": [118.02, 39.63],"平顶山": [113.29, 33.75],"邢台": [114.48, 37.05],"德州": [116.29, 37.45],"济宁": [116.59, 35.38],"荆州": [112.239741, 30.335165],"宜昌": [111.3, 30.7],"义乌": [120.06, 29.32],"丽水": [119.92, 28.45],"洛阳": [112.44, 34.7],"秦皇岛": [119.57, 39.95],"株洲": [113.16, 27.83],"石家庄": [114.48, 38.03],"莱芜": [117.67, 36.19],"常德": [111.69, 29.05],"保定": [115.48, 38.85],"湘潭": [112.91, 27.87],"金华": [119.64, 29.12],"岳阳": [113.09, 29.37],"长沙": [113, 28.21],"衢州": [118.88, 28.97],"廊坊": [116.7, 39.53],"菏泽": [115.480656, 35.23375],"合肥": [117.27, 31.86],"武汉": [114.31, 30.52],"大庆": [125.03, 46.58],}def convert_data():res = []for i in range(len(data)):geo_coord = geoCoordMap[data[i][0]]geo_coord.append(data[i][1])res.append([data[i][0], geo_coord])return res(BMap(init_opts=opts.InitOpts(width="1200px", height="800px")) .add(type_="effectScatter",series_name="pm2.5",data_pair=convert_data(),symbol_size=10,effect_opts=opts.EffectOpts(),label_opts=opts.LabelOpts(formatter="{b}", position="right", is_show=False),itemstyle_opts=opts.ItemStyleOpts(color="purple"), ) .add_schema(baidu_ak="FAKE_AK",center=[104.114129, 37.550339],zoom=5,is_roam=True,map_style={"styleJson": [ {"featureType": "water","elementType": "all","stylers": {"color": "#044161"}, }, {"featureType": "land","elementType": "all","stylers": {"color": "#004981"}, }, {"featureType": "boundary","elementType": "geometry","stylers": {"color": "#064f85"}, }, {"featureType": "railway","elementType": "all","stylers": {"visibility": "off"}, }, {"featureType": "highway","elementType": "geometry","stylers": {"color": "#004981"}, }, {"featureType": "highway","elementType": "geometry.fill","stylers": {"color": "#005b96", "lightness": 1}, }, {"featureType": "highway","elementType": "labels","stylers": {"visibility": "off"}, }, {"featureType": "arterial","elementType": "geometry","stylers": {"color": "#004981"}, }, {"featureType": "arterial","elementType": "geometry.fill","stylers": {"color": "#00508b"}, }, {"featureType": "poi","elementType": "all","stylers": {"visibility": "off"}, }, {"featureType": "green","elementType": "all","stylers": {"color": "#056197", "visibility": "off"}, }, {"featureType": "subway","elementType": "all","stylers": {"visibility": "off"}, }, {"featureType": "manmade","elementType": "all","stylers": {"visibility": "off"}, }, {"featureType": "local","elementType": "all","stylers": {"visibility": "off"}, }, {"featureType": "arterial","elementType": "labels","stylers": {"visibility": "off"}, }, {"featureType": "boundary","elementType": "geometry.fill","stylers": {"color": "#029fd4"}, }, {"featureType": "building","elementType": "all","stylers": {"color": "#1a5787"}, }, {"featureType": "label","elementType": "all","stylers": {"visibility": "off"}, }, ] }, ) .set_global_opts(title_opts=opts.TitleOpts(title="全国主要城市空气质量",subtitle="data from PM25.in",subtitle_link="http://www.pm25.in",pos_left="center",title_textstyle_opts=opts.TextStyleOpts(color="#fff"), ),tooltip_opts=opts.TooltipOpts(trigger="item"), ) .render("air_quality_baidu_map.html"))
目前还是以熟悉为主,多多借鉴官网上的代码,能够有效提升自己的构图水平!
柱状图构建
1.基础柱状图
掌握构建一个基础的柱状图并能够反转x和y轴
通过Bar构建基础柱状图
from pyecharts.charts import Barfrom pyecharts.options import *# 构建柱状图对象bar = Bar()# 添加x轴数据bar.add_xaxis(["中国","美国","英国"])# 添加y轴数据bar.add_yaxis("GDP",[30, 20, 10])# 绘图bar.render("基础柱状图.html")
如果想要反转x、y轴的话,实际上只需要用到bar.reversal_axis()即可
from pyecharts.charts import Barfrom pyecharts.options import *# 构建柱状图对象bar = Bar()# 添加x轴数据bar.add_xaxis(["中国","美国","英国"])# 添加y轴数据bar.add_yaxis("GDP",[30, 20, 10])# 反转x、y轴bar.reversal_axis()# 绘图bar.render("基础柱状图.html")
为了将数字标签全都移到右边,我们可以在其中增加相应的label_opts="right"
from pyecharts.charts import Barfrom 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("基础柱状图.html")
2.基础时间线柱状图
Timeline()——时间线
柱状图描述的是分类数据,回答的是每一个分类中「有多少?」这个问题。这是柱状图的主要特点,同时柱状图很难动态的描述一个趋势性的数据.这里pyecharts.为我们提供了一种解决方案——时间线
如果说一个Bar、Line对象是一张图表的话,时间线就是创建一个一维的x轴,轴上每一个点就是一个图表对象。
创建时间线的代码:
from pyecharts.charts import Bar, Timelinefrom pyecharts.options import *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, 30, 20], label_opts=LabelOpts(position="right"))bar2.reversal_axis()bar3 = Bar()bar3.add_xaxis(["中国","美国","英国"])bar3.add_yaxis("GDP",[70, 50, 40], label_opts=LabelOpts(position="right"))bar3.reversal_axis()# 创建时间线对象timeline = Timeline()# timeline对象添加bar柱状图timeline.add(bar1,"2021年GDP")timeline.add(bar2,"2022年GDP")timeline.add(bar3,"2023年GDP")# 通过时间线绘图timeline.render("基础柱状图-时间线.html")
下面的时间线可以来回移动,显示2021或者2022的GDP数据。
如果想要添加自动播放功能的话,可以加上下面的设置代码
# 设置自动播放timeline.add_schema(play_interval=1000,# 自动播放的时间间隔,单位毫秒is_timeline_show=True,# 是否在自动播放的时候,显示时间线is_auto_play=True,# 是否自动播放is_loop_play=True# 是否循环自动播放)
加上主题的话,可以再增加,如下是目前该可视化代码的完整版本啦:
from pyecharts.charts import Bar, Timelinefrom pyecharts.options import *from pyecharts.globals import ThemeTypebar1 = 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, 30, 20], label_opts=LabelOpts(position="right"))bar2.reversal_axis()bar3 = Bar()bar3.add_xaxis(["中国","美国","英国"])bar3.add_yaxis("GDP",[70, 50, 40], label_opts=LabelOpts(position="right"))bar3.reversal_axis()# 创建时间线对象timeline = Timeline({"theme":ThemeType.ESSOS})# timeline对象添加bar柱状图timeline.add(bar1,"2021年GDP")timeline.add(bar2,"2022年GDP")timeline.add(bar3,"2023年GDP")# 设置自动播放timeline.add_schema(play_interval=1000,# 自动播放的时间间隔,单位毫秒is_timeline_show=True,# 是否在自动播放的时候,显示时间线is_auto_play=True,# 是否自动播放is_loop_play=True# 是否循环自动播放)# 通过时间线绘图timeline.render("基础柱状图-时间线.html")
3.GDP动态柱状图绘制
列表的sort方法
在前面我们学习过sorted函数,可以对数据容器进行排序。
在后面的数据处理中,我们需要对列表进行排序,并指定排序规则,sorted函数就无法完成了。
我们补充学习列表的sort方法。
使用方式:
列表.sort(key=选择排序依据的函数, reverse=True|False)
参数key,是要求传入一个函数,表示将列表的每一个元素都传入函数中,返回排序的依据
参数reverse,是否反转排序结果,True表示降序,False表示升序
列表的sort方法:
带名函数形式
# 准备列表my_list = [["a",33],["b",55],["c",11]]# 排序,基于带名函数# 定义排序的方法def choose_sort_key(element):return element[1]my_list.sort(key=choose_sort_key, reverse=True)print(my_list)
[['b', 55], ['a', 33], ['c', 11]]
需求分析:
简单分析后,发现最终效果图中需要:
GDP数据处理为亿级
有时间轴,按照年份为时间轴的点
x轴和y轴反转,同时每一年的数据只要前8名国家
有标题,标题的年份会动态更改
设置了主题为LIGHT
首先先编一个GDP数据,存储在记事本上,至于是否合理暂且不论,嘿嘿。
"""演示第三个图表:GDP动态柱状图开发"""from pyecharts.charts import Bar, Timelinefrom pyecharts.options import *# 读取数据f = open("C:/Users/asus/Desktop/C2唐祎敏学习笔记/黑马Python/test文件/1960-2019年全球八国GDP数据.txt","r",encoding="UTF-8")data_lines = f.readlines()f.close()data_lines.pop(0)# 先定义一个字典对象data_dict = {}for line in data_lines:year = int(line.split(",")[0])country = line.split(",")[1]gdp = float(line.split(",")[2])# 判断字典keytry: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)# 取出本年份前8名国家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()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}年全球前8GDP数据") )timeline.add(bar, str(year))# 时间自动播放timeline.add_schema(play_interval=1000,is_timeline_show=True,is_auto_play=True,is_loop_play=False)timeline.render("1960~2020全国GDP前8国家.html")
有亿点点夸张,嘿嘿,但是我们确实实现了这个可视化图像
下面是我捏造的数据:
year,GDP,rate1960,美国,5.433E+111960,英国,732339676921960,法国,622254780001960,中国,597164676251960,日本,443073429501960,加拿大,404617216921960,意大利,403852883441960,印度,370298838751960,澳大利亚,185776682711960,瑞典,158225850331960,巴西,151655699121960,土耳其,139950678171960,墨西哥,130400000001960,荷兰,122767341721960,西班牙,120721260751960,比利时,116587225901960,瑞士,95227467191960,委内瑞拉,77790909091960,南非,75753969721960,菲律宾,66845688051960,奥地利,65926938411960,丹麦,62489468801960,新西兰,54858547911960,芬兰,52241021951960,挪威,51632715981960,希腊,43351860161960,孟加拉,42748939131960,伊朗,41991343901960,尼日利亚,41960922581960,智利,41100000001960,哥伦比亚,40311529761960,韩国,39581907581960,巴基斯坦,37492650141960,刚果(金),33594041171960,葡萄牙,31932004041960,泰国,27607474711960,阿尔及利亚,27236485511960,以色列,25985000001960,秘鲁,25719080621960,摩洛哥,20371507161960,爱尔兰,19393297751960,马来西亚,19162419961960,波多黎各,16919000001970,美国,6.433E+111970,英国,832339676921970,法国,722254780001970,中国,697164676251970,日本,543073429501970,加拿大,504617216921970,意大利,503852883441970,印度,470298838751970,澳大利亚,285776682711970,瑞典,258225850331970,巴西,351655699121970,土耳其,239950678171970,墨西哥,230400000001970,荷兰,222767341721970,西班牙,120721260751970,比利时,196587225901970,瑞士,105227467191970,委内瑞拉,79790909091970,南非,85753969721970,菲律宾,76845688051970,奥地利,75926938411970,丹麦,72489468801970,新西兰,64858547911970,芬兰,62241021951970,挪威,61632715981970,希腊,53351860161970,孟加拉,52748939131970,伊朗,51991343901970,尼日利亚,51860922581970,智利,41000000001970,哥伦比亚,47311529761970,韩国,46581907581970,巴基斯坦,47492650141970,刚果(金),43594041171970,葡萄牙,41932004041970,泰国,37607474711970,阿尔及利亚,37236485511970,以色列,35985000001970,秘鲁,25019080621970,摩洛哥,30371507161970,爱尔兰,29393297751970,马来西亚,29162419961970,波多黎各,26919000001980,美国,8.433E+111980,英国,732339676921980,法国,622254780001980,中国,2.971E+111980,日本,443073429501980,加拿大,404617216921980,意大利,403852883441980,印度,370298838751980,澳大利亚,185776682711980,瑞典,158225850331980,巴西,151655699121980,土耳其,139950678171980,墨西哥,130400000001980,荷兰,122767341721980,西班牙,120721260751980,比利时,116587225901980,瑞士,95227467191980,委内瑞拉,77790909091980,南非,75753969721980,菲律宾,66845688051980,奥地利,65926938411980,丹麦,62489468801980,新西兰,54858547911980,芬兰,52241021951980,挪威,51632715981980,希腊,43351860161980,孟加拉,42748939131980,伊朗,41991343901980,尼日利亚,41960922581980,智利,41100000001980,哥伦比亚,40311529761980,韩国,39581907581980,巴基斯坦,37492650141980,刚果(金),33594041171980,葡萄牙,31932004041980,泰国,27607474711980,阿尔及利亚,27236485511980,以色列,25985000001980,秘鲁,25719080621980,摩洛哥,20371507161980,爱尔兰,19393297751980,马来西亚,19162419961980,波多黎各,16919000001990,美国,1.433E+121990,英国,732339676921990,法国,622254780001990,中国,8.342E+101990,日本,443073429501990,加拿大,404617216921990,意大利,403852883441990,印度,370298838751990,澳大利亚,185776682711990,瑞典,158225850331990,巴西,151655699121990,土耳其,139950678171990,墨西哥,130400000001990,荷兰,122767341721990,西班牙,120721260751990,比利时,116587225901990,瑞士,95227467191990,委内瑞拉,77790909091990,南非,75753969721990,菲律宾,66845688051990,奥地利,65926938411990,丹麦,62489468801990,新西兰,54858547911990,芬兰,52241021951990,挪威,51632715981990,希腊,43351860161990,孟加拉,42748939131990,伊朗,41991343901990,尼日利亚,41960922581990,智利,41100000001990,哥伦比亚,40311529761990,韩国,39581907581990,巴基斯坦,37492650141990,刚果(金),33594041171990,葡萄牙,31932004041990,泰国,27607474711990,阿尔及利亚,27236485511990,以色列,25985000001990,秘鲁,25719080621990,摩洛哥,20371507161990,爱尔兰,19393297751990,马来西亚,19162419961990,波多黎各,16919000002000,美国,1.433E+132000,英国,732339676922000,法国,622254780002000,中国,5.971E+122000,日本,443073429502000,加拿大,404617216922000,意大利,403852883442000,印度,370298838752000,澳大利亚,185776682712000,瑞典,158225850332000,巴西,151655699122000,土耳其,139950678172000,墨西哥,130400000002000,荷兰,122767341722000,西班牙,120721260752000,比利时,116587225902000,瑞士,95227467192000,委内瑞拉,77790909092000,南非,75753969722000,菲律宾,66845688052000,奥地利,65926938412000,丹麦,62489468802000,新西兰,54858547912000,芬兰,52241021952000,挪威,51632715982000,希腊,43351860162000,孟加拉,42748939132000,伊朗,41991343902000,尼日利亚,41960922582000,智利,41100000002000,哥伦比亚,40311529762000,韩国,39581907582000,巴基斯坦,37492650142000,刚果(金),33594041172000,葡萄牙,31932004042000,泰国,27607474712000,阿尔及利亚,27236485512000,以色列,25985000002000,秘鲁,25719080622000,摩洛哥,20371507162000,爱尔兰,19393297752000,马来西亚,19162419962000,波多黎各,16919000002010,美国,5.433E+142010,英国,732339676922010,法国,622254780002010,中国,1.971E+142010,日本,443073429502010,加拿大,404617216922010,意大利,403852883442010,印度,370298838752010,澳大利亚,185776682712010,瑞典,158225850332010,巴西,151655699122010,土耳其,139950678172010,墨西哥,130400000002010,荷兰,122767341722010,西班牙,120721260752010,比利时,116587225902010,瑞士,95227467192010,委内瑞拉,77790909092010,南非,75753969722010,菲律宾,66845688052010,奥地利,65926938412010,丹麦,62489468802010,新西兰,54858547912010,芬兰,52241021952010,挪威,51632715982010,希腊,43351860162010,孟加拉,42748939132010,伊朗,41991343902010,尼日利亚,41960922582010,智利,41100000002010,哥伦比亚,40311529762010,韩国,39581907582010,巴基斯坦,37492650142010,刚果(金),33594041172010,葡萄牙,31932004042010,泰国,27607474712010,阿尔及利亚,27236485512010,以色列,25985000002010,秘鲁,25719080622010,摩洛哥,20371507162010,爱尔兰,19393297752010,马来西亚,19162419962010,波多黎各,16919000002020,美国,5.433E+142020,英国,732339676922020,法国,622254780002020,中国,5.971E+142020,日本,443073429502020,加拿大,404617216922020,意大利,403852883442020,印度,370298838752020,澳大利亚,185776682712020,瑞典,158225850332020,巴西,151655699122020,土耳其,139950678172020,墨西哥,130400000002020,荷兰,122767341722020,西班牙,120721260752020,比利时,116587225902020,瑞士,95227467192020,委内瑞拉,77790909092020,南非,75753969722020,菲律宾,66845688052020,奥地利,65926938412020,丹麦,62489468802020,新西兰,54858547912020,芬兰,52241021952020,挪威,51632715982020,希腊,43351860162020,孟加拉,42748939132020,伊朗,41991343902020,尼日利亚,41960922582020,智利,41100000002020,哥伦比亚,40311529762020,韩国,39581907582020,巴基斯坦,37492650142020,刚果(金),33594041172020,葡萄牙,31932004042020,泰国,27607474712020,阿尔及利亚,27236485512020,以色列,25985000002020,秘鲁,25719080622020,摩洛哥,20371507162020,爱尔兰,19393297752020,马来西亚,19162419962020,波多黎各,1691900000