起因
早上逛公众号看到有个库plotly
做可视化很厉害,早上闲来无事就研究下,后面发现还要注册账号,直接劝退,结果被我找到他的一个高级封装库叫plotly_express
,也有神器的名号,那就这个吧~
安装
pip命令
pip install plotly_express
相关链接
参考博文
https://www.jianshu.com/p/41735ecd3f75
https://www.jianshu.com/p/44416202aafb
http://liyangbit.com/pythonvisualization/Plotly-Express-introduction-cn/
官方文档
https://plotly.com/python/plotly-express/
上手
散点图
一个最简单的散点图实现:
import plotly_express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
用的数据源是内置且很常见的鸢尾花数据集,效果长这样:
在此基础上,可以通过添加更多的关键字参数来丰富图像的内容。
trendline
参数可以添加预测的趋势线,现在可选的值有两个ols
和lowess
,前者是线性的最小二乘回归模型,后者是非线性的局部加权回归模型,具体算法我也不明,反正一个用于线性一个用于非线性呗。
template
就不用多赘述了吧,可选值有这些["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"]
,选自己喜欢的就好。
error_x
和error_y
代表了误差线,传入值跟x y
参数一样都是数据源的列名,所以需要先在DF
上面计算出来。
marginal_x
和marginal_y
看效果是在添加一个水平/垂直方向的子图,可选项有这些 rug(细条)、box(箱图)、violin(小提琴图)、histogram(直方图)
。
还有很多牛逼的参数像animation_frame
和 facet_col
这些你可以通过help(px.scatter)
一一查询,每个参数都介绍得挺清楚的,要是有中文翻译就好了呜呜。
他官网上面最终的散点图长这样:
import plotly_express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin",
marginal_x="box", trendline="ols", template="simple_white")
fig.show()
折线图
import plotly_express as px
import numpy as np
t = np.linspace(0, 2*np.pi, 100)
fig = px.line(x=t, y=np.cos(t), labels={'x':'t', 'y':'cos(t)'})
fig.show()
import plotly_express as px
df = px.data.gapminder().query("continent == 'Oceania'")
fig = px.line(df, x='year', y='lifeExp', color='country')
fig.show()
如果你想要折线图能够圆滑一点,就不是那种尖尖,可以设置这两个参数 render_mode="svg"
和 line_shape="spline"
,像这样:
px.line(gapminder, x="year", y="lifeExp", color="continent",
line_group="country", hover_name="country",
line_shape="spline", render_mode="svg")
条形图
import plotly_express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.show()
如果很多行数据在x轴维度上拥有同样的值,矩形会默认地一个一个堆叠起来,更改参数barmode
即可。添加facet_row
和facet_col
参数产生多面的子图:
import plotly_express as px
fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group",
facet_row="time", facet_col="day",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
"time": ["Lunch", "Dinner"]})
fig.show()
散点矩阵
import plotly_express as px
df = px.data.iris()
fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species")
fig.show()
可以通过fig.update_traces(diagonal_visible=False)
把对角线的子图隐藏掉。
平行坐标图
import plotly_express as px
df = px.data.iris()
fig = px.parallel_coordinates(df, color="species_id", labels={"species_id": "Species",
"sepal_width": "Sepal Width", "sepal_length": "Sepal Length",
"petal_width": "Petal Width", "petal_length": "Petal Length", },
color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=2)
fig.show()
看起来很高级的样子,不知道哪里能用得到。
直方图
px.histogram(tips, x="total_bill", y="tip", color="sex", marginal="rug", histfunc="avg",
hover_data=tips.columns)
特别一点的参数有 histfunc
,默认值是 count
,可选值有 count/sum/avg/min/max
。histnorm
默认为 None,不对数据做任何处理,可选值有 percent/probability/density/probability density
,前两个算出占比,后两个算密度。
箱型图
px.box(tips, x="day", y="total_bill", color="smoker", notched=True)
箱型图的boxmode
默认值就是group
,不像直方图和条形图,notched
参数代表了图像有没有缺口
小提琴图
px.violin(tips, y="tip", x="smoker", color="sex", box=True, points="all",
hover_data=tips.columns)
小提琴图和箱型图的组合总是让人不忍直视,所以没图。
其他图
还有很多图就稍微提一下,用的没上面多。三元散点图(scatter_ternary)、三元线条图(line_ternary)、三维散点图(scatter_3d)、极坐标散点图(scatter_polar)、极坐标线条图(line_polar)、极坐标条形图(bar_polar)、地理坐标散点图(scatter_geo)、地理坐标线条图(line_geo)、等高值区域地图(choropleth)等。
进阶 - update
Plotly_express 的输出,继承自 Plotly.py 的 Figure 类 ExpressFigure 的对象,这意味着可以使用任何 Figure 的访问器和方法,来改变 px 生成的图表,通常借助于 .update() 函数来调用。
update的用法可太多了,下面列举一下我用过的,以后慢慢补充吧:
# 对y轴的数据做升序排列,配合animation_frame可以做一个简陋的动画,对每一帧都排序。
fig.update_yaxes(categoryorder='total ascending')
# 设置y轴上字体的大小和角度
fig.update_yaxes(tickfont=dict(size=15),tickangle=-45)
# 设置条形图text的样式和位置(默认是在里面)
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
# 设置标题
fig.update_layout(barmode='relative',title='asd')