data visualization
Visualization effect 1: The cumulative number of confirmed cases of the new crown in India, the United States and Japan in 2020
2020 is the year of the outbreak of the new crown epidemic. With the outbreak of the epidemic, the number of confirmed cases at home and abroad has become a hot spot of concern. I believe everyone has seen similar epidemic reports. This case is a comparison of the number of confirmed cases in India, the United States, and Japan. Visualization processing was carried out to form a visualized report on the number of confirmed cases of the epidemic.
Visualization effect 2: Visualization of the national epidemic map
Visualization 3: Dynamic GDP growth graph
There is no way to make dynamic changes here. I hope everyone can imagine by themselves, and then start visual learning.
1. JSON data conversion
JSON is a lightweight data interaction format that can organize and encapsulate data in the format specified by JSON
JSON is essentially a string with a specific format
Main functions: json is a data format that circulates in various programming languages. It is responsible for data transmission and interaction in different programming languages. It is similar to: the international common language-English, the common language of 56 ethnic groups in different regions of China-Mandarin
Various programming languages store data in different containers. In Python, there are data types such as dictionaries dict, while other languages may not have corresponding dictionaries.
In order to allow different languages to communicate with each other, JSON is a very good data transfer format.
JSON format data conversion
The format of #json data can be: {"name":"admin","age":18} # can also be: [{"name":"admin","age":18},{"name":"root","age":16},{"name":"张三","age":20}]
To put it bluntly, the json format is a python list or dictionary. The only requirement is that the nested inside the list must be a dictionary. Second, there are no format or form requirements for the dictionary itself.
json is essentially a string.
Mutual conversion between Python data and Json data
Familiarize yourself with this knowledge point through code
List nested dictionary form :
# 导入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)
If it contains Chinese, then add ensure_ascii=False
Dictionary form :
import json
# 准备字典,将字典转换为Json
d = {"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. Introduction to pyecharts module
Overview:
Echarts is a data visualization open sourced by Baidu. With its good interactivity and exquisite chart design, it has been recognized by many developers. And Python is an expressive language, which is very suitable for data processing. When data analysis meets data visualization, pyecharts was born.
Open the official website pyecharts.org
Then open a gallery function website Document
pyecharts module installation
The PyEcharts module can be quickly installed using the pip command learned earlier
Open the command prompt and enter pip install pyecharts
Then enter python, then import import pyecharts
It is displayed here, indicating that there is no error in the installation and it can be used normally.
3. Quick start of pyecharts
1. Basic line chart
# 导包,导入Line功能构建折线图对象
from pyecharts.charts import Line
# 得到折线图对象
line = Line()
# 添加x轴数据
line.add_xaxis(["中国","美国","英国"])
# 添加y轴数据
line.add_yaxis("GDP",[30,20,10])
# 生成图表
line.render()
After building our line chart and running it, you will find that render.html appears in the file column next to it. Click the web page function of this file to view the corresponding web page function.
2. Configuration options of pyecharts
Global configuration options :
set_global_opts method:
Here, the global configuration options can be configured through the set_global_opts method, and the corresponding options and options are as follows:
When we have completed the chart, we can pass the set_global_opts method
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), )
On the basis of our original above, perform the following operations:
-
Configure the title of the chart
-
configuration legend
-
Configure mouse movement effects
-
Configure Toolbar
-
other overall configuration items
# 导包,导入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()
After checking, you will find that the visualization diagram of this global configuration is quite good. Of course, to further improve this diagram and introduce more global configuration content, then you need to understand it through the official website of pyecharts.
3. Data processing
Open a website ab173, which is a lazy tool website. Find the Json view in it, and then you can store the data you selected in the following formatter, click Verify or press Enter to operate, at this time, you can click the view to integrate a large number of contents into corresponding dictionaries and lists package form.
Many required data can be displayed and simulated through third-party websites.
Open pycharm and encode accordingly:
import json
from pyecharts.charts import Line
from 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 key
trend_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()
Open the json view again, and place our simplified content in the Json view of the website, you can view
Unfortunately, I don't have the corresponding data files and content for the time being, and there is no way to display the visualization on the web page.
Visualization case
1. Map - base map use
Basic map demo :
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts
map = 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()
Through the ab173 website, find the rgb color comparison table in the front end
2. Construction of national epidemic map
Although there is no corresponding data, it does not prevent us from familiarizing and operating the code. Let us open pychart
"""
演示全国疫情可视化地图开发
"""
import json
from pyecharts.charts import Map
from 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. Mapping of air quality in Zhejiang Province
import json
from pyecharts.charts import Map
from 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. Imitate Baidu air visualization
The following is Baidu's air quality visualization map:
import pyecharts.options as opts
from pyecharts.charts import BMap
data = [
["海门", 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")
)
At present, it is still based on familiarity. Learn more from the code on the official website, which can effectively improve your composition level!
Histogram construction
1. Basic histogram
Master building a basic histogram with the ability to invert the x and y axes
Build a basic histogram through Bar
from pyecharts.charts import Bar
from pyecharts.options import *
# 构建柱状图对象
bar = Bar()
# 添加x轴数据
bar.add_xaxis(["中国","美国","英国"])
# 添加y轴数据
bar.add_yaxis("GDP",[30, 20, 10])
# 绘图
bar.render("基础柱状图.html")
If you want to reverse the x and y axes, you actually only need to use bar.reversal_axis()
from pyecharts.charts import Bar
from 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")
To move the number labels all to the right, we can add the correspondinglabel_opts="right"
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("基础柱状图.html")
2. Basic timeline histogram
Timeline() - Timeline
Histograms describe categorical data and answer the question "How many?" in each category. This is the main feature of the histogram. At the same time, it is difficult for the histogram to describe a trending data dynamically. Here pyecharts. Provide us with a solution - timeline
If a Bar and Line object is a chart, the timeline is to create a one-dimensional x-axis, and each point on the axis is a chart object.
Code to create the timeline :
from pyecharts.charts import Bar, Timeline
from 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")
The timeline below can be moved back and forth to show GDP data for 2021 or 2022.
If you want to add autoplay function, you can add the following setting code
# 设置自动播放
timeline.add_schema(
play_interval=1000,# 自动播放的时间间隔,单位毫秒
is_timeline_show=True,# 是否在自动播放的时候,显示时间线
is_auto_play=True,# 是否自动播放
is_loop_play=True# 是否循环自动播放
)
If you add a theme, you can add more. The following is the complete version of the current visualization code:
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
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, 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 dynamic histogram drawing
list sort method
We have learned the sorted function earlier, which can sort data containers.
In the subsequent data processing, we need to sort the list and specify the sorting rules, and the sorted function cannot be completed.
We complement the sort method of learning lists.
How to use:
列表.sort(key=选择排序依据的函数, reverse=True|False)
The parameter key is required to pass in a function, which means that each element of the list is passed into the function, and the basis for sorting is returned
Parameter reverse, whether to reverse the sorting result, True means descending order, False means ascending order
The sort method of the list :
named function form
# 准备列表
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]]
Demand analysis :
After a simple analysis, it is found that the final rendering needs:
-
GDP data is processed at the level of 100 million
-
There is a time axis, according to the year as the point of the time axis
-
The x-axis and y-axis are reversed, and the data for each year only needs the top 8 countries
-
There is a title, and the year of the title will change dynamically
-
Set theme to LIGHT
First of all, compile a GDP data and store it in a notepad. As for whether it is reasonable or not, hehe.
"""
演示第三个图表:GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from 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])
# 判断字典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)
# 取出本年份前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")
A little exaggeration, hey, but we did achieve this visualization
Here is my fudged data:
year,GDP,rate 1960, USA, 5.433E+11 1960,UK,73233967692 1960,France,62225478000 1960,China,59716467625 1960, Japan, 44307342950 1960,Canada,40461721692 1960,Italy,40385288344 1960,India,37029883875 1960,Australia,18577668271 1960,Sweden,15822585033 1960,Brazil,15165569912 1960,Türkiye,13995067817 1960,Mexico,13040000000 1960,Netherlands,12276734172 1960,Spain,12072126075 1960,Belgium,11658722590 1960,Switzerland,9522746719 1960,Venezuela,7779090909 1960,South Africa,7575396972 1960,Philippines,6684568805 1960,Austria,6592693841 1960,Denmark,6248946880 1960,New Zealand,5485854791 1960,Finland,5224102195 1960,Norway,5163271598 1960,Greece,4335186016 1960,Bangladesh,4274893913 1960,Iran,4199134390 1960,Nigeria,4196092258 1960,Chile,4110000000 1960,Colombia,4031152976 1960, South Korea, 3958190758 1960,Pakistan,3749265014 1960, Congo (Kinshasa), 3359404117 1960,Portugal,3193200404 1960,Thailand,2760747471 1960,Algeria,2723648551 1960,Israel,2598500000 1960,Peru,2571908062 1960,Morocco,2037150716 1960, Ireland, 1939329775 1960,Malaysia,1916241996 1960,Puerto Rico,1691900000 1970, USA, 6.433E+11 1970,UK,83233967692 1970,France,72225478000 1970, China, 69716467625 1970, Japan, 54307342950 1970,Canada,50461721692 1970,Italy,50385288344 1970,India,47029883875 1970,Australia,28577668271 1970, Sweden, 25822585033 1970,Brazil,35165569912 1970,Türkiye,23995067817 1970,Mexico,23040000000 1970,Netherlands,22276734172 1970,Spain,12072126075 1970, Belgium, 19658722590 1970,Switzerland,10522746719 1970,Venezuela,7979090909 1970,South Africa,8575396972 1970,Philippines,7684568805 1970,Austria,7592693841 1970,Denmark,7248946880 1970,New Zealand,6485854791 1970,Finland,6224102195 1970,Norway,6163271598 1970,Greece,5335186016 1970,Bangladesh,5274893913 1970,Iran,5199134390 1970,Nigeria,5186092258 1970,Chile,4100000000 1970,Colombia,4731152976 1970,Korea,4658190758 1970,Pakistan,4749265014 1970, Congo (Kinshasa), 4359404117 1970,Portugal,4193200404 1970,Thailand,3760747471 1970,Algeria,3723648551 1970,Israel,3598500000 1970,Peru,2501908062 1970,Morocco,3037150716 1970,Ireland,2939329775 1970,Malaysia,2916241996 1970,Puerto Rico,2691900000 1980, USA, 8.433E+11 1980,UK,73233967692 1980,France,62225478000 1980, China, 2.971E+11 1980, Japan, 44307342950 1980,Canada,40461721692 1980,Italy,40385288344 1980,India,37029883875 1980,Australia,18577668271 1980,Sweden,15822585033 1980,Brazil,15165569912 1980,Türkiye,13995067817 1980,Mexico,13040000000 1980,Netherlands,12276734172 1980,Spain,12072126075 1980,Belgium,11658722590 1980,Switzerland,9522746719 1980,Venezuela,7779090909 1980,South Africa,7575396972 1980,Philippines,6684568805 1980,Austria,6592693841 1980,Denmark,6248946880 1980, New Zealand, 5485854791 1980,Finland,5224102195 1980,Norway,5163271598 1980,Greece,4335186016 1980,Bangladesh,4274893913 1980,Iran,4199134390 1980,Nigeria,4196092258 1980,Chile,4110000000 1980,Colombia,4031152976 1980,Korea,3958190758 1980,Pakistan,3749265014 1980, Congo (Kinshasa), 3359404117 1980,Portugal,3193200404 1980,Thailand,2760747471 1980,Algeria,2723648551 1980, Israel, 2598500000 1980,Peru,2571908062 1980,Morocco,2037150716 1980,Ireland,1939329775 1980,Malaysia,1916241996 1980,Puerto Rico,1691900000 1990, USA, 1.433E+12 1990,UK,73233967692 1990, France, 62225478000 1990, China, 8.342E+10 1990, Japan, 44307342950 1990,Canada,40461721692 1990,Italy,40385288344 1990,India,37029883875 1990,Australia,18577668271 1990,Sweden,15822585033 1990,Brazil,15165569912 1990,Türkiye,13995067817 1990,Mexico,13040000000 1990,Netherlands,12276734172 1990,Spain,12072126075 1990,Belgium,11658722590 1990,Switzerland,9522746719 1990,Venezuela,7779090909 1990,South Africa,7575396972 1990,Philippines,6684568805 1990,Austria,6592693841 1990,Denmark,6248946880 1990, New Zealand, 5485854791 1990,Finland,5224102195 1990, Norway, 5163271598 1990,Greece,4335186016 1990,Bangladesh,4274893913 1990,Iran,4199134390 1990, Nigeria, 4196092258 1990, Chile, 4110000000 1990,Colombia,4031152976 1990, South Korea, 3958190758 1990,Pakistan,3749265014 1990, Congo (Kinshasa), 3359404117 1990,Portugal,3193200404 1990,Thailand,2760747471 1990,Algeria,2723648551 1990, Israel, 2598500000 1990,Peru,2571908062 1990,Morocco,2037150716 1990, Ireland, 1939329775 1990,Malaysia,1916241996 1990,Puerto Rico,1691900000 2000, USA, 1.433E+13 2000,UK,73233967692 2000,France,62225478000 2000, China, 5.971E+12 2000, Japan, 44307342950 2000,Canada,40461721692 2000,Italy,40385288344 2000,India,37029883875 2000,Australia,18577668271 2000, Sweden, 15822585033 2000,Brazil,15165569912 2000,Türkiye,13995067817 2000,Mexico,13040000000 2000,Netherlands,12276734172 2000,Spain,12072126075 2000,Belgium,11658722590 2000,Switzerland,9522746719 2000,Venezuela,7779090909 2000, South Africa, 7575396972 2000,Philippines,6684568805 2000,Austria,6592693841 2000,Denmark,6248946880 2000, New Zealand, 5485854791 2000,Finland,5224102195 2000, Norway, 5163271598 2000,Greece,4335186016 2000,Bangladesh,4274893913 2000,Iran,4199134390 2000, Nigeria, 4196092258 2000,Chile,4110000000 2000,Colombia,4031152976 2000, South Korea, 3958190758 2000,Pakistan,3749265014 2000, Congo (Kinshasa), 3359404117 2000,Portugal,3193200404 2000,Thailand,2760747471 2000,Algeria,2723648551 2000,Israel,2598500000 2000,Peru,2571908062 2000,Morocco,2037150716 2000,Ireland,1939329775 2000,Malaysia,1916241996 2000,Puerto Rico,1691900000 2010, USA, 5.433E+14 2010,UK,73233967692 2010, France, 62225478000 2010, China, 1.971E+14 2010, Japan, 44307342950 2010,Canada,40461721692 2010,Italy,40385288344 2010,India,37029883875 2010, Australia, 18577668271 2010, Sweden, 15822585033 2010,Brazil,15165569912 2010,Türkiye,13995067817 2010, Mexico, 13040000000 2010,Netherlands,12276734172 2010,Spain,12072126075 2010,Belgium,11658722590 2010, Switzerland, 9522746719 2010,Venezuela,7779090909 2010, South Africa, 7575396972 2010,Philippines,6684568805 2010, Austria, 6592693841 2010, Denmark, 6248946880 2010, New Zealand, 5485854791 2010,Finland,5224102195 2010, Norway, 5163271598 2010, Greece, 4335186016 2010, Bangladesh, 4274893913 2010,Iran,4199134390 2010, Nigeria, 4196092258 2010, Chile, 4110000000 2010,Colombia,4031152976 2010, South Korea, 3958190758 2010, Pakistan, 3749265014 2010, Congo (Kinshasa), 3359404117 2010,Portugal,3193200404 2010,Thailand,2760747471 2010, Algeria, 2723648551 2010, Israel, 2598500000 2010,Peru,2571908062 2010, Morocco, 2037150716 2010,Ireland,1939329775 2010, Malaysia, 1916241996 2010,Puerto Rico,1691900000 2020, United States, 5.433E+14 2020,UK,73233967692 2020, France, 62225478000 2020, China, 5.971E+14 2020, Japan, 44307342950 2020,Canada,40461721692 2020,Italy,40385288344 2020,India,37029883875 2020, Australia, 18577668271 2020, Sweden, 15822585033 2020, Brazil, 15165569912 2020, Türkiye, 13995067817 2020,Mexico,13040000000 2020,Netherlands,12276734172 2020,Spain,12072126075 2020,Belgium,11658722590 2020, Switzerland, 9522746719 2020,Venezuela,7779090909 2020, South Africa, 7575396972 2020,Philippines,6684568805 2020, Austria, 6592693841 2020, Denmark, 6248946880 2020, New Zealand, 5485854791 2020,Finland,5224102195 2020, Norway, 5163271598 2020, Greece, 4335186016 2020, Bangladesh, 4274893913 2020,Iran,4199134390 2020, Nigeria, 4196092258 2020,Chile,4110000000 2020,Colombia,4031152976 2020,Korea,3958190758 2020,Pakistan,3749265014 2020, Congo (Kinshasa), 3359404117 2020,Portugal,3193200404 2020,Thailand,2760747471 2020, Algeria, 2723648551 2020,Israel,2598500000 2020,Peru,2571908062 2020, Morocco, 2037150716 2020,Ireland,1939329775 2020, Malaysia, 1916241996 2020,Puerto Rico,1691900000