Plotly Express in Python

来源:https://mp.weixin.qq.com/s/dg390bbxA_LEoggWg6dGlQ

Plotly Express 是一个新的高级 Python 可视化库:它是 Plotly.py 的高级封装,它为复杂的图表提供了一个简单的语法。

受 Seaborn 和 ggplot2 的启发,它专门设计为具有简洁,一致且易于学习的 API :只需一次导入,您就可以在一个函数调用中创建丰富的交互式绘图,包括分面绘图(faceting)、地图、动画和趋势线。它带有数据集、颜色面板和主题,就像 Plotly.py 一样。Plotly是新一代的可视化神器,由TopQ量化团队开源。虽然Ploltly功能非常之强大,但是一直没有得到重视,主要原因还是其设置过于繁琐。因此,Plotly推出了其简化接口:Plotly_express,下文中统一简称为px。

Plotly Express 完全免费:凭借其宽松的开源 MIT 许可证,您可以随意使用它(是的,甚至在商业产品中!)。

最重要的是,Plotly Express 与 Plotly 生态系统的其他部分完全兼容:在您的 Dash 应用程序中使用它,使用 Orca 将您的数据导出为几乎任何文件格式,或使用JupyterLab 图表编辑器在 GUI 中编辑它们!

https://plotly.com/python/plotly-express/

安装plotly_express

pip install plotly_express
Collecting plotly_express
  Downloading plotly_express-0.4.1-py2.py3-none-any.whl (2.9 kB)
Requirement already satisfied: plotly>=4.1.0 in /opt/anaconda3/lib/python3.7/site-packages (from plotly_express) (4.11.0)
Requirement already satisfied: patsy>=0.5 in /opt/anaconda3/lib/python3.7/site-packages (from plotly_express) (0.5.1)
Requirement already satisfied: numpy>=1.11 in /opt/anaconda3/lib/python3.7/site-packages (from plotly_express) (1.18.1)
Requirement already satisfied: pandas>=0.20.0 in /opt/anaconda3/lib/python3.7/site-packages (from plotly_express) (1.0.1)
Requirement already satisfied: statsmodels>=0.9.0 in /opt/anaconda3/lib/python3.7/site-packages (from plotly_express) (0.11.0)
Requirement already satisfied: scipy>=0.18 in /opt/anaconda3/lib/python3.7/site-packages (from plotly_express) (1.4.1)
Requirement already satisfied: six in /opt/anaconda3/lib/python3.7/site-packages (from plotly>=4.1.0->plotly_express) (1.14.0)
Requirement already satisfied: retrying>=1.3.3 in /opt/anaconda3/lib/python3.7/site-packages (from plotly>=4.1.0->plotly_express) (1.3.3)
Requirement already satisfied: python-dateutil>=2.6.1 in /opt/anaconda3/lib/python3.7/site-packages (from pandas>=0.20.0->plotly_express) (2.8.1)
Requirement already satisfied: pytz>=2017.2 in /opt/anaconda3/lib/python3.7/site-packages (from pandas>=0.20.0->plotly_express) (2019.3)
Installing collected packages: plotly-express
Successfully installed plotly-express-0.4.1
Note: you may need to restart the kernel to use updated packages.

导入数据

import pandas as pd
import numpy as np
import plotly.express as px  

# 数据集
gapminder = px.data.gapminder()
gapminder.head()  # 取出前5条数据
country continent year lifeExp pop gdpPercap iso_alpha iso_num
0 Afghanistan Asia 1952 28.801 8425333 779.445314 AFG 4
1 Afghanistan Asia 1957 30.332 9240934 820.853030 AFG 4
2 Afghanistan Asia 1962 31.997 10267083 853.100710 AFG 4
3 Afghanistan Asia 1967 34.020 11537966 836.197138 AFG 4
4 Afghanistan Asia 1972 36.088 13079460 739.981106 AFG 4
gapminder.shape
(1704, 8)

可视化示例

# line 图
fig = px.line(
  gapminder,  # 数据集
  x="year",  # 横坐标
  y="lifeExp",  # 纵坐标
  color="continent",  # 颜色的数据
  line_group="continent",  # 线性分组
  hover_name="country",   # 悬停hover的数据
  line_shape="spline",  # 线的形状
  render_mode="svg"  # 生成的图片模式
)
fig.show()