pyecharts 是一个用于生成 Echarts 图表的类库。Echarts 是百度开源的一个数据可视化 JS 库。用 Echarts 生成的图可视化效果非常棒,pyecharts 是为了与 Python 进行对接,方便在 Python 中直接使用数据生成图。
今天我们就用jupyter notebook(工具)和pyecharts(库)绘制图形
一、Pyecharts绘制饼图
from pyecharts.charts import Pie
import pyecharts.options as opts
num = [110, 136, 108, 111, 112, 103]
lab = ['哈士奇', '萨摩耶', '泰迪', '金毛', '牧羊犬', '吉娃娃']
# 创建饼图
pie_chart = (
Pie(init_opts=opts.InitOpts(width='720px', height='320px'))
.add("", [(j, i) for i, j in zip(num, lab)])
.set_global_opts(title_opts=opts.TitleOpts(title="狗狗种类分布"))
.render("pie_chart.html") # 保存为 HTML 文件
)
# 导入库
from pyecharts.charts import Pie
from pyecharts import options as opts
#数据
x_data = ['张三','李四','王五','赵六']
y_data = [830,214,300,1100]
# Pie 设置指定的格式
data_pair = [list(z) for z in list(zip(x_data,y_data))] # [['张三', 830], ['李四', 214], ['王五', 300], ['赵六', 1100]]
c = Pie(init_opts=opts.InitOpts(width='500px',height='500px'))
c.add(series_name='访问来源',data_pair=data_pair,radius=['40%','75%']) #radius 讲饼图展示位环形图
# 设置全局项
c.set_global_opts(title_opts=opts.TitleOpts(title='测试数据',pos_left='center',pos_top=20),
legend_opts=opts.LegendOpts(orient='vertical',pos_top='15%',pos_left='2%')) #图例
# 设置每项数据占比
c.set_series_opts(tooltip_opts=opts.TooltipOpts(trigger='item',formatter="{a} <br/> {b}:{c} ({d}%)")) #formatter 图表悬停时数据展示格式化
c.render("环图.html")
二、Pyecharts绘制柱状图
from pyecharts.charts import Bar
import pyecharts.options as opts
num = [110, 136, 108, 48, 111, 112, 103]
lab = ['哈士奇', '萨摩耶', '泰迪', '金毛', '牧羊犬', '吉娃娃', '柯基']
(
Bar(init_opts=opts.InitOpts(width='720px', height='320px'))
.add_xaxis(xaxis_data=lab)
.add_yaxis(series_name='', y_axis=num) # 将参数名改为 y_axis
.render("bar_chart.html") # 将图表保存为 HTML 文件
)
三、Pyecharts绘制地理迁移图
from pyecharts.charts import Geo,Map
import pyecharts.options as opts
from pyecharts.globals import ChartType,SymbolType
city_num = [('广州',105),('成都',105),('北京',105),('西安',105)]
start_end = [('广州','成都'),('广州','北京'),('广州','西安')]
(
Geo()
.add_schema(maptype='china',#设置地图类型
itemstyle_opts = opts.ItemStyleOpts(color='#323c48',#设置背景颜色
border_color='#111'))#边界颜色
.add('',data_pair = city_num,color = 'white')#添加数据,默认是点
.add('',data_pair=start_end,type_=ChartType.LINES,#把start_end用线描绘
effect_opts=opts.EffectOpts(symbol=SymbolType.ARROW, #把特效的线改成箭头
color='blue',
symbol_size=8 #箭头的大小
)
)
).render("qinxi.html")
四、折线图
#导入相关库
import pyecharts.options as opts #全局变量设置
from pyecharts.charts import Line #折线图
#数据
x = ['seaborn','matplotlib','plotly','pyecharts','python']
y1 = [440,550,770,450,800]
y2 = [570,1340,1370,1111,2222]
#用函数来绘制图形
c = Line()
c.add_xaxis(xaxis_data=x) #x轴数值
c.add_yaxis(series_name='',y_axis=y1) #y轴数值与标签设置
c.add_yaxis(series_name='',y_axis=y2)
#对工具箱中名称修改
data_zoom = {
"show":True,
"title":{"zoom":"data zoom","back":"data zoom restore"}
}
#set_global_opts全局变量设置
c.set_global_opts(
title_opts=opts.TitleOpts(title='测试数据'), #图表标题
legend_opts=opts.LegendOpts(is_show=True), #图例为True时展示
tooltip_opts=opts.TooltipOpts(trigger='axis',axis_pointer_type='cross'), #触发类型,就是鼠标悬停在图表上时显示的内容
toolbox_opts=opts.ToolboxOpts(is_show=True,orient='horizontal',
feature=opts.ToolBoxFeatureOpts(data_zoom=data_zoom))#显示工具箱(下载图片、转换图形为柱状图、刷新等)
)
c.render_notebook() #在jupyter notebook中生成图形
五、热点词云
# 导入库
import pyecharts.options as opts
from pyecharts.charts import WordCloud
# 数据
data = [
('python', 4583345),
('excel', 2324539),
('人工智能', 2296099),
('机器学习', 1376545),
('深度学习', 1337607),
('mysql', 4583345),
('数据', 5324539),
('数据分析', 3296099),
('数据挖掘', 1376545)
]
c = WordCloud()
c.add(series_name='图表', data_pair=data)
c.set_global_opts(title_opts=opts.TitleOpts(title='热词展示'))
c.render("reci.html")
七、动态GDP图
"""
演示第三个图表:GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType
# 读取数据
f = open("D:/1960-2019全球GDP数据.csv", "r", encoding="GB2312")
data_lines = f.readlines()
# 关闭文件
f.close()
# 删除第一条数据
data_lines.pop(0)
# 将数据转换为字典存储,格式为:
# { 年份: [ [国家, gdp], [国家,gdp], ...... ], 年份: [ [国家, gdp], [国家,gdp], ...... ], ...... }
# { 1960: [ [美国, 123], [中国,321], ...... ], 1961: [ [美国, 123], [中国,321], ...... ], ...... }
# 先定义一个字典对象
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])
# print(data_dict[1960])
# 创建时间线对象
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]) # 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}年全球前8GDP数据")
)
timeline.add(bar, str(year))
# for循环每一年的数据,基于每一年的数据,创建每一年的bar对象
# 在for中,将每一年的bar对象添加到时间线中
# 设置时间线自动播放
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_auto_play=True,
is_loop_play=False
)
# 绘图
timeline.render("1960-2019全球GDP前8国家.html")
八、中国地图
"""
演示全国疫情可视化地图开发
"""
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"]
# 组装每个省份和确诊人数为元组,并各个省的数据都封装入列表内
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))
# 创建地图对象
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~9999人", "color": "#FFFF99"},
{"min": 1000, "max": 4999, "lable": "1000~4999人", "color": "#FF9966"},
{"min": 5000, "max": 9999, "lable": "5000~99999人", "color": "#FF6666"},
{"min": 10000, "max": 99999, "lable": "10000~99999人", "color": "#CC3333"},
{"min": 100000, "lable": "100000+", "color": "#990033"},
]
)
)
# 绘图
map.render("全国疫情地图.html")