Plotly Python 相比较seaborn,matplotlib等,最吸引用户的,当属他的交互属性。所谓交互,不仅仅指鼠标滑过是标签信息的展示,更多的是图例的联动、鼠标框选范围后数据的动态缩放,可以满足业务人员日常工作中对数据的审查与洞察。
工欲善其事必先利其器。要用好plotly,通读官方文档是少不了的。
Plotly 是一个图像的创建(create)、精修(manipulate)、渲染(render)的过程。官方推荐的入手工具包为plotly.express,但是对于复杂图形,例如多个子图subplots of different types,双/多坐标轴dual-axis plots,或者分图faceted plots,还是得回归鼻祖plotly.graph_objects.Figure。
简单而言,一个图像由三大类核心元素构成,分别为data,layout, frames。
data 说到data元素,要提一个名词,叫trace。不知道怎么翻译这个词,望文生义,暂时理解为是所有data属性下子元素的集合,冠名为trace。
trace中需明确图形类型type:目前支持的图形类型超过40种,包含:scatter, bar, pie等;每个trace 会当做一个subplot来看待,除非使用subplots定义;每个trace 可定制设置图例legend;部分trace type 支持continuous color 设置layout 顾名思义,layout可个性化配置除数据之前所有,比如位置,标题,坐标轴,背景色。背景线等等。举例如下:
dimensions and margins,页边距的细节性配置。Plotly采用的不是精确地像素级定位,而是采用relative positioning,默认图形位置起点(0,0),终点(1,1)。可通过layout.margin调整;template font color 等全局设置设置title legend:标题和图例设置系列颜色 color axes and associated color bars设置子图subplots参数给数据区域增加点评文字annotation(平时业务场景中常用)给数据区域增加参考线、警戒线、辅助线等 shapes给数据区域增加背景图images高阶使用:增加控制按钮undatemenus: single buttons toggles dropdown menus slider controls,有点驾驶舱产品的感觉了。frame 主要用于annimated plot中。
纸上得来终觉浅,绝知此事要躬行。要想深入细致体会个个属性、自参数,还是要多作图,多感受,多总结,多思考。
在作图之前,先说图形的导出和使用,貌似有点本末倒置。但是考虑到身处“结果导向性”社会,会哭的孩子有奶吃,会秀的同事赛西施。结果到位了,才关心过程和细节。
一般来说,在jupyter notebook中作图后,可以选择静态图片导出fig.write_image('image_name.png'),也可以选择动态html导出 fig.write_html('file_name.html').
导出之前新建文件夹:新建文件夹有什么好处,不言而喻。
import os if not os.path.exists("conda_images"): os.mkdir("conda_images")后续导出文件时,在文件名称前增加文件夹名称即可
fig1.write_html('conda_images/scatter_exercise.html')对于怎么画图,官方给了两种方式,一种叫Figure as Dictionaries,一种叫Figures as Graph Object。 大多数时候,我们用的是第二种,包括使用plotly express plotly.graph_objects figure_factory make subplots 等等。
接下来以简单的条形图bar为例。
数据预览
df=px.data.gapminder() df.head()3. 绘制中国历年人口变化图
fig=px.bar(df.query('country=="China"'),x='year',y='pop') fig.show()这个环节就是为图形增加所有可读性的元素。
标题 fig.update_layout(title_text='中国人口变迁史', title_x=.5, font=dict(family='simsun', size=14, color='#1d39c4') )2. 坐标轴axis
fig.update_layout(xaxis_title='年份', yaxis_title='人口数量')3. 柱形图数值显示
fig=px.bar(df.query('country=="China"'),x='year',y='pop',text='pop', #增加柱形图文字信息 color_discrete_sequence=['#2f54eb'], hover_name='year' #增加hover_name ) #柱形图文字格式 fig.update_traces( textposition='outside', texttemplate='%{text:,.2s}')4. 修改系列颜色
fig=px.bar(df.query('country=="China"'),x='year',y='pop',color_discrete_sequence=['#2f54eb']) 修改轮播标签信息 初级版:突出显示系列信息 fig=px.bar(df.query('country=="China"'),x='year',y='pop', color_discrete_sequence=['#2f54eb'], hover_name='year' #增加hover_name )进阶版:显示非系列信息,如显示数据集lifeExp gdpPercap信息。
#利用customdata增加数据集 fig.update_traces(customdata=df[['lifeExp','gdpPercap']]) fig.update_traces(hovertemplate='Year: %{x}<br><br> Population: %{y}<br> Life Expectation: %{customdata[0]:,.2f}<br>GDP per capital: %{customdata[1]:,.2f}')6. 坐标轴tick 设置
fig.update_xaxes(tickangle=-45, tickfont=dict(family='arial', size=12))7. 增加annotation
fig.add_annotation(x='1982', y=1000281000, text='突破10亿', font=dict(color='red')) fig.update_annotations(dict(xref='x', yref='y', showarrow=True), arrowcolor='red', arrowhead=4)此部分作图结束。完整代码如下:
fig=px.bar(df.query('country=="China"'),x='year',y='pop',text='pop', color_discrete_sequence=['#2f54eb'], hover_name='year', #增加hover_name ) fig.update_layout(title_text='中国人口变迁史', title_x=.5, font=dict(family='simsun', size=14, color='#1d39c4') ) fig.update_layout(xaxis_title='年份', yaxis_title='人口数量') fig.update_traces( textposition='outside', texttemplate='%{text:,.2s}') #利用customdata增加数据集 fig.update_traces(customdata=df[['lifeExp','gdpPercap']]) fig.update_traces(hovertemplate='Year: %{x}<br><br> Population: %{y}<br> Life Expectation: %{customdata[0]:,.2f}<br>GDP per capital: %{customdata[1]:,.2f}') fig.update_xaxes(tickangle=-45, tickfont=dict(family='arial', size=12)) #dtick=1) fig.update_layout(bargap=.4, uniformtext_minsize=8, uniformtext_mode='show') fig.add_annotation(x='1982', y=1000281000, text='突破10亿', font=dict(color='red')) fig.update_annotations(dict(xref='x', yref='y', showarrow=True), arrowcolor='red', arrowhead=4) fig.show()Plotly 可以支持的图形类型很多。对于一般的分析场景,基础类、统计类、财务类,再加上子图,即可满足大部分的使用场景。
后续会在kaggle上选一个数据案例,进行各类型图形作图的分享。