1,pycharts模块介绍
2,pycharts快速入门
pycharts模块
如果想要做出数据可视化效果图,可以借助pyecharts模块来完成
基础折线图
通过Line构建折线图
#导包,导入line功能构建折线图对象
from pyecharts.charts import Line
#Line()表示得到折线图对象
line = Line() #代码运行到这里时出现一个空的坐标系
#添加X轴数据
line.add_xaxis(['语文','数学','英语'])
#添加Y轴数据
line.add_yaxis('成绩分布',[90,98,92])
#生成折线图
line.render()
在谷歌浏览器的呈现结果为
pyecharts中的配置选项
pyecharts中有很多常用配置项,常用两项为:全局配置选项、系列配置选项(此处选择全局配置项举例)
全局配置项可以通过set_global_opts方法来进行配置,相应的选项和功能有:
TitleOpts:标题配置项
LegendOpts:图例配置项
ToolOpts:工具栏配置项
代码展示
#导包,导入line功能构建折线图对象
from pyecharts.charts import Line
from pyecharts.options import TitleOpts,LegendOpts,ToolboxOpts,VisualMapOpts #通过逗号导入多个功能
#Line()表示得到折线图对象
line = Line() #代码运行到这里时出现一个空的坐标系
#添加X轴数据
line.add_xaxis(['语文','数学','英语'])
#添加Y轴数据
line.add_yaxis('成绩分布',[90,98,92])
#设置全局配置项set_global_opts来设置
line.set_global_opts(
title_opts=TitleOpts(title='成绩分布',pos_lceft='center',pos_bottom='1%'),
#pos为position表示位置,pos_left表示距离左侧的距离
# pos_bottom表示距离底部的距离
legend_opts=LegendOpts(is_show=True),
toolbox_opts=ToolboxOpts(is_show=True),
visualmap_opts=VisualMapOpts(is_show=True) #视觉映射
#is_show通过True和False控制是否展示
)
#生成折线图
line.render()
在谷歌浏览器中的呈现结果:
为图列配置项,默认显示
为标题控制项,可以通过pos_left()和pos_bottom()来控制位置
为工具栏配置项,可通过点击第三个图标显示数据试图,如图所示
为视觉映射配置项,可以通过点击分数显示在视觉映射中的位置
地图
通过Map构建地图
代码展示
#演示地图可视化的基本使用
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts #导入地图视觉映射功能
#Map()表示地图对象
map = Map()
#准备数据
data = [
('黑龙江省',3),
('天津市',14),
('北京市',16),
('安徽省',20),
('浙江省',24),
('江西省',25)
]
#导入数据
map.add('城市温度分布',data,'china')
#“测试地图”表示地图对象名称,data表示数据,“china”表示地图类型(默认为中国地图)
#设置全局选项
map.set_global_opts(
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True, #手动矫正视觉映射范围
pieces=[
{'min':1,'max':10,'label':'1~10℃','color':'#CCFFFF'},
{'min':11,'max':20,'label':'11~20℃','color':'#FF6666'},
{'min':21,'max':30,'label':'21~30℃','color':'#990033'}
]
)
)
#绘制地图
map.render()
在谷歌浏览器中的呈现结果:
柱状图
#演示柱状图的使用
from pyecharts.charts import Bar
from pyecharts.options import LabelOpts
#构建柱状图对象
bar = Bar()
#添加x轴数据
bar.add_xaxis(['语文','数学','英语'])
#添加y轴数据
#通过使用label_opts=LabelOpts(position='right')使数值标签显示在柱状图的右侧
bar.add_yaxis('成绩分布',[92,98,90],label_opts=LabelOpts(position='right'))
#通过使用reversal_axis()函数反转x,y轴
bar.reversal_axis()
#绘制柱状图
bar.render()
在谷歌浏览器中的呈现结果:
动态柱状图
from pyecharts.charts import Bar,Timeline
from pyecharts.options import LabelOpts
bar1 = Bar()
bar1.add_xaxis(['语文','数学','英语'])
bar1.add_yaxis('成绩分布',[92,98,90],label_opts=LabelOpts(position='right'))
bar2 = Bar()
bar2.add_xaxis(['语文','数学','英语'])
bar2.add_yaxis('成绩分布',[95,100,92],label_opts=LabelOpts(position='right'))
#构建时间对象
timeline = Timeline()
#在时间线内添加柱状图对象
timeline.add(bar1,'第一学期')
timeline.add(bar2,'第二学期')
#绘图使用时间线对象绘图,而不是bar对象
#绘制动态柱状图
timeline.render()
运行结果