每日一包 - pyecharts(快速上手)

380 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第29天,点击查看活动详情

介绍

pyecharts 是一个用于生成 Echarts 图表的类库。Echarts 是百度开源的一个数据可视化 JS 库。用 Echarts 生成的图可视化效果非常棒,为了与 Python 进行对接,方便在 Python 中直接使用数据生成图。

包括常用的30多种常见图表,可以轻松的集成到Python主流web框架比如django flask中,并且该模块的官方文档中文非常友好~

关于pyecharts将分成两篇文章进行介绍。

安装和使用

安装

pyecharts 分为 v0.5.X 和 v1 两个大版本,v0.5.X 和 v1 间不兼容,v1 是一个全新的版本,新版本系列将从 v1.0.0 开始,文档位于 pyecharts.org

同样可以使用两种方式进行安装:

  • pip安装

pip install pyecharts

  • 源码安装
$ git clone https://github.com/pyecharts/pyecharts.git
$ cd pyecharts
$ pip install -r requirements.txt
$ python setup.py install
# 或者执行 python install.py

使用

快速上手

通过下述代码可以非常快速的实现第一个柱状图表:

from pyecharts.charts import Bar
​
bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,如 bar.render("mycharts.html")
bar.render()

效果图如下:

img

pytecharts中所有的方法都支持链式调用:

from pyecharts.charts import Bar
​
bar = (
    Bar()
    .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
)
bar.render()

可以通过使用options为图表设置主标题和副标题:

from pyecharts.charts import Bar
​
bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.set_global_opts(title_opts=opts.TitleOpts(title="主标题", subtitle="副标题"))
bar.render()

效果图如下:

img

还可以为生成的图表选择主题样式,在pyecharts中内置了10+种主题,当然也可以定制自己喜欢的主题,定制主题这里不进行详细介绍啦。

from pyecharts.charts import Bar
from pyecharts import options as opts
# 内置主题类型可查看 pyecharts.globals.ThemeType
from pyecharts.globals import ThemeType
​
bar = (
    Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
    .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
    .add_yaxis("商家B", [15, 6, 45, 20, 35, 66])
    .set_global_opts(title_opts=opts.TitleOpts(title="主标题", subtitle="副标题"))
)

有了主题样式的图表样式如下:

img

总结

在使用 Pandas&Numpy时,请确保将数值类型转换为 python 原生的 int/float。比如整数类型请确保为 int,而不是 numpy.int32pyecharts的图表功能非常好用,本文先介绍该模块的快速使用,更加详细的用法可以参考该模块的官方文档进行学习~